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: 11110110101100000000 Answer: 1 Example 2: 11000110000010000011 Answer: 3
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
Solution
publicclassSolution {publicintnumIslands(char[][] grid) {int result =0;int m =grid.length;if (m ==0) return0;int n = grid[0].length;boolean[][] visited =newboolean[m][n];for(int i =0; i < m; i ++) {for(int j =0; j < n; j ++) {if (grid[i][j] =='1'&&!visited[i][j]) { result ++;dfs(grid, visited, i,j,m,n); } } }return result; }publicvoiddfs(char[][] grid,boolean[][] visited,int x,int y,int m,int n) { visited[x][y] =true;if (isValid(x +1, y, m, n)&&!visited[x +1][y] && grid[x +1][y] =='1') {dfs(grid, visited, x +1, y, m, n); }if (isValid(x -1, y, m, n)&&!visited[x -1][y] && grid[x -1][y] =='1') {dfs(grid, visited, x -1, y, m, n); }if (isValid(x, y +1, m, n)&&!visited[x][y +1] && grid[x][y +1] =='1') {dfs(grid, visited, x, y +1, m, n); }if (isValid(x, y -1, m, n)&&!visited[x][y -1] && grid[x][y -1] =='1') {dfs(grid, visited, x, y -1, m, n); } }publicbooleanisValid(int x,int y,int m,int n) {return x >=0&& x <= m -1&& y >=0&& y <= n -1; }}