@@ -0,0 +1,1593 @@
+package depth_first_search;%0A%0Apublic class NumberOfIslands %7B%0A%0A    //TAG: Google%0A    //TAG: Facebook%0A    //TAG: Microsoft%0A    //TAG: Amazon%0A    //TAG: DFS%0A    //TAG: BFS%0A    //Difficulty: medium%0A%0A    /**%0A     * 200. Number of Islands%0A     * 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.%0A%0A     Example 1:%0A%0A     11110%0A     11010%0A     11000%0A     00000%0A     Answer: 1%0A%0A     Example 2:%0A%0A     11000%0A     11000%0A     00100%0A     00011%0A     Answer: 3%0A     */%0A%0A    /**%0A     * Solution:%0A     * DFS, when find a '1', try to set all adjacent '1' to '0' (including itself)%0A     *%0A     * Then when met another 1, it must be another island%0A     *%0A     * Time: O(2mn)%0A     * Space: O(1)%0A     */%0A%0A    public int numIslands(char%5B%5D%5B%5D grid) %7B%0A        int count = 0;%0A        if (grid == null %7C%7C grid.length == 0) return 0;%0A        for (int i = 0; i %3C grid.length; i++) %7B%0A            for (int j = 0; j %3C grid%5B0%5D.length; j++) %7B%0A                if (grid%5Bi%5D%5Bj%5D == '1') %7B%0A                    dfs(grid, i, j);%0A                    count++;%0A                %7D%0A            %7D%0A        %7D%0A        return count;%0A    %7D%0A%0A    private void dfs(char%5B%5D%5B%5D grid, int i, int j) %7B%0A        if (i %3C 0 %7C%7C j %3C 0 %7C%7C i %3E= grid.length %7C%7C j %3E= grid%5B0%5D.length %7C%7C grid%5Bi%5D%5Bj%5D != '1') return;%0A        grid%5Bi%5D%5Bj%5D = '0';%0A        dfs(grid, i - 1, j);%0A        dfs(grid, i, j - 1);%0A        dfs(grid, i + 1, j);%0A        dfs(grid, i, j + 1);%0A    %7D%0A%0A%7D%0A

200. Number of Islands