Title Link: number-of-islands
/** * 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 are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water. Example 1:11110110101100000000answer:1example 2:11000110000010000011answer:3 * */public class NumberOfIslands {//45/4 5 test Cases passed.//status:accepted//runtime:298 ms//submitted:0 minutes ago////time complexity O (n ^ 2), Space complexity O (1) public int Numislands (char[][] grid) {int m = grid.length; if (M = = 0) return 0; int n = grid[0].length; int islands = 0; for (int i = 0; i < m; i + +) {for (int j = 0; J < N; j + +) {if (grid[i][j] = = ' 1 ') {Islands + +;d fs (grid, I, j); }}} return islands; } public void Dfs (char[][] grid, int i, int j) {if (I < 0 | | i = = Grid.length | | J < 0 | | j = grid[0].length) return;//validation within the matrix range if (grid[i][j] = = ' 1 ') {grid[i][j] = ' 0 ';/marked as visited Dfs (grid, I-1, j);//Left DFS (grid, i + 1, j);//Right Dfs (grid, I, j-1);//DFS (grid, I, j + 1);//Next} }public static void Main (string[] args) {//TODO auto-generated method stub}}
[Leetcode 200] Number of Islands