Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int countConnections(List<List<Integer>> matrix) {
- int m = matrix.size();
- if (m == 0) return 0;
- int n = matrix.get(0).size();
- // Only these 4 directions to avoid double-counting:
- int[][] directions = {
- {0, 1}, // right
- {1, 0}, // down
- {1, 1}, // down-right
- {1, -1} // down-left
- };
- int count = 0;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (matrix.get(i).get(j) == 1) {
- for (int[] dir : directions) {
- int ni = i + dir[0];
- int nj = j + dir[1];
- if (ni >= 0 && ni < m && nj >= 0 && nj < n && matrix.get(ni).get(nj) == 1) {
- count++;
- }
- }
- }
- }
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement