Given a matrix with 1s and 0s, please find the number of groups of 1s. A group is defined by horizontally or vertically adjacent 1s. For example, there are four groups of 1s in figure below.
Analysis: Use DFS.
public class NumberOfGroups { public static void main(String[] args) { int[][] input = {{1, 1, 0, 0, 1}, {1, 0 ,0 , 1, 0}, {1, 1, 0, 1, 0}, {0, 0, 1, 0, 0}}; System.out.println(new NumberOfGroups().getNumberofGroups(input)); } public int getNumberofGroups(int[][] input) { boolean[][] visited = new boolean[input.length][input[0].length]; int count = 0; for (int i = 0; i < input.length; i++) { for (int j = 0; j < input[0].length; j++) { if (input[i][j] == 1 && visited[i][j] == false) { count++; traverse(input, visited, i, j); } } } return count; } public void traverse(int[][] input, boolean[][] visited, int i, int j) { visited[i][j] = true; if (i - 1 >= 0 && visited[i - 1][j] == false && input[i - 1][j] == 1) { traverse(input, visited, i - 1, j); } if (i + 1 < input.length && visited[i + 1][j] == false && input[i + 1][j] == 1) { traverse(input, visited, i + 1, j); } if (j - 1 >= 0 && visited[i][j - 1] == false && input[i][j - 1] == 1) { traverse(input, visited, i, j - 1); } if (j + 1 < input[0].length && visited[i][j + 1] == false && input[i][j + 1] == 1) { traverse(input, visited, i, j + 1); } } }