Given a 2d grid map of'1's (land) and'0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
2. Implementation
(1) BFS
classSolution {publicintnumIslands(char[][] grid) {if (grid ==null||grid.length==0) {return0; }int[][] directions = {{0,-1}, {0,1}, {-1,0}, {1,0}};int m =grid.length, n = grid[0].length;int count =0;for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {if (grid[i][j] =='1') {++count;searchByBFS(grid, i, j, m, n, directions); } } }return count; }publicvoidsearchByBFS(char[][] grid,int row,int col,int m,int n,int[][] directions) { grid[row][col] ='0';Queue<Integer> queue =newLinkedList<>();queue.add(row * n + col);while (!queue.isEmpty()) {int curPoint =queue.remove();int curRow = curPoint / n;int curCol = curPoint % n;for (int[] direction : directions) {int nextRow = curRow + direction[0];int nextCol = curCol + direction[1];if (isValid(grid, nextRow, nextCol)) { grid[nextRow][nextCol] ='0';queue.add(nextRow * n + nextCol); } } } }publicbooleanisValid(char[][] grid,int row,int col) {return row >=0&& row <grid.length&& col >=0&& col < grid[0].length&& grid[row][col] =='1'; }}