package leetcode;

/**
 * https://leetcode.com/problems/count-servers-that-communicate/
 */
public class Problem1267 {
    public int countServers(int[][] grid) {
        int answer = 0;
        int nRows = grid.length;
        int nCols = nRows > 0 ? grid[0].length : 0;
        for (int i = 0; i < nRows; i++) {
            int count = 0;
            for (int j = 0; j < nCols; j++) {
                if (grid[i][j] == 1) {
                    count++;
                }
            }
            if (count > 1) {
                answer += count;
            }
        }
        for (int i = 0; i < nCols; i++) {
            int count = 0;
            for (int j = 0; j < nRows; j++) {
                if (grid[j][i] == 1) {
                    count++;
                }
            }
            if (count > 1) {
                answer += count;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem1267 prob = new Problem1267();
//        System.out.println(prob.countServers(new int[][]{{1,0},{0,1}})); // 0
        System.out.println(prob.countServers(new int[][]{{1,0},{1,1}})); // 3
//        System.out.println(prob.countServers(new int[][]{{1,1,0,0},{0,0,1,0},{0,0,1,0},{0,0,0,1}})); // 4
    }
}

@@ -261,24 +261,81 @@
 length : 0;%0A
+        boolean%5B%5D%5B%5D visited = new boolean%5BnRows%5D%5BnCols%5D;%0A
         for 
@@ -383,32 +383,80 @@
  int count = 0;%0A
+            boolean%5B%5D tmp = new boolean%5BnCols%5D;%0A
             for 
@@ -516,32 +516,67 @@
 d%5Bi%5D%5Bj%5D == 1) %7B%0A
+                    tmp%5Bj%5D = true;%0A
                 
@@ -641,32 +641,66 @@
 f (count %3E 1) %7B%0A
+                visited%5Bi%5D = tmp;%0A
                 
@@ -801,32 +801,62 @@
  int count = 0;%0A
+            int nVisited = 0;%0A
             for 
@@ -940,32 +940,44 @@
             
-count++;
+if (visited%5Bj%5D%5Bi%5D) %7B
 %0A           
@@ -977,34 +977,32 @@
             
-%7D%0A
         
     %7D%0A      
@@ -981,37 +981,43 @@
                 
-    %7D
+nVisited++;
 %0A            if 
@@ -1013,32 +1013,25 @@
         
-if (count %3E 1) %7B
+        %7D
 %0A       
@@ -1039,33 +1039,33 @@
         
-answer += count;%0A
+    count++;%0A    
         
@@ -1082,396 +1082,133 @@
     
-%7D%0A
     
+%7D%0A
     
-return answer;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem1267 prob = new Problem1267();%0A//        System.out.println(prob.countServers(new int%5B%5D%5B%5D%7B%7B1,0%7D,%7B0,1%7D%7D)); // 0%0A        System.out.println(prob.countServers(new int%5B%5D%5B%5D%7B%7B1,0%7D,%7B1,1%7D%7D)); // 3%0A//        System.out.println(prob.countServers(new int%5B%5D%5B%5D%7B%7B1,1,0,0%7D,%7B0,0,1,0%7D,%7B0,0,1,0%7D,%7B0,0,0,1%7D%7D)); // 4
+        if (count %3E 1) %7B%0A                answer += count - nVisited;%0A            %7D%0A        %7D%0A        return answer;
 %0A   

Solve problem 1267