Given a boolean 2D matrix,0is represented as the sea,1is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
需要掌握BFS和DFS的方法,在遍历的同时进行改动原值mark by bfs/dfs,dfs会有爆栈的可能,bfs会更好一些
Time: O(MN), Space: O(MN)
Code
classCoordinate {int x, y;publicCoordinate(int x,int y) {this.x= x;this.y= y; }}publicclassSolution { /** * @param grid a boolean 2D matrix * @return an integer */publicintnumIslands(boolean[][] grid) {if (grid ==null||grid.length==0|| grid[0].length==0) {return0; }int n =grid.length;int m = grid[0].length;int islands =0;for (int i =0; i < n; i++) {for (int j =0; j < m; j++) {if (grid[i][j]) {markByBFS(grid, i, j); islands++; } } }return islands; }privatevoidmarkByBFS(boolean[][] grid,int x,int y) {// magic numbers!int[] directionX = {0,1,-1,0};int[] directionY = {1,0,0,-1};Queue<Coordinate> queue =newLinkedList<>();queue.offer(newCoordinate(x, y)); grid[x][y] =false;while (!queue.isEmpty()) {Coordinate coor =queue.poll();for (int i =0; i <4; i++) {Coordinate adj =newCoordinate(coor.x+ directionX[i],coor.y+ directionY[i] );if (!inBound(adj, grid)) {continue; }if (grid[adj.x][adj.y]) { grid[adj.x][adj.y] =false;queue.offer(adj); } } } }privatebooleaninBound(Coordinate coor,boolean[][] grid) {int n =grid.length;int m = grid[0].length;returncoor.x>=0&&coor.x< n &&coor.y>=0&&coor.y< m; }}
publicclassSolution { /** * @param grid a boolean 2D matrix * @return an integer */privateint m, n;publicvoiddfs(boolean[][] grid,int i,int j) {if (i <0|| i >= m || j <0|| j >= n) return;if (grid[i][j]) { grid[i][j] =false;dfs(grid, i -1, j);dfs(grid, i +1, j);dfs(grid, i, j -1);dfs(grid, i, j +1); } }publicintnumIslands(boolean[][] grid) {// Write your code here m =grid.length;if (m ==0) return0; n = grid[0].length;if (n ==0) return0;int ans =0;for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {if (!grid[i][j]) continue; ans++;dfs(grid, i, j); } }return ans; }}