Advertisement
asdfg0998

Untitled

May 11th, 2025
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. public static int countConnections(List<List<Integer>> matrix) {
  2.         int m = matrix.size();
  3.         if (m == 0) return 0;
  4.         int n = matrix.get(0).size();
  5.  
  6.         // Only these 4 directions to avoid double-counting:
  7.         int[][] directions = {
  8.             {0, 1},   // right
  9.             {1, 0},   // down
  10.             {1, 1},   // down-right
  11.             {1, -1}   // down-left
  12.         };
  13.  
  14.         int count = 0;
  15.  
  16.         for (int i = 0; i < m; i++) {
  17.             for (int j = 0; j < n; j++) {
  18.                 if (matrix.get(i).get(j) == 1) {
  19.                     for (int[] dir : directions) {
  20.                         int ni = i + dir[0];
  21.                         int nj = j + dir[1];
  22.  
  23.                         if (ni >= 0 && ni < m && nj >= 0 && nj < n && matrix.get(ni).get(nj) == 1) {
  24.                             count++;
  25.                         }
  26.                     }
  27.                 }
  28.             }
  29.         }
  30.  
  31.         return count;
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement