leetcode Number of Islands

题目链接

思路:
广度优先搜索

代码

public class Solution {
    public int numIslands(char[][] grid) {
         int count=0;
        for(int i=0;i<grid.length;i++)
        {
            for(int j=0;j<grid[0].length;j++)
            {
                if(grid[i][j]=='1')
                {
                    count++;
                    dfs(grid, i, j);
                }

            }
        }
        return count;
    }

    public void dfs(char[][]grid,int rowIndex,int columIndex)
    {
        if(rowIndex<0||rowIndex>grid.length-1)
        {
            return;
        }

        if(columIndex<0||columIndex>grid[0].length-1)
        {
            return;
        }

        if(grid[rowIndex][columIndex]=='0')
        {
            return;
        }

        grid[rowIndex][columIndex]='0';
        dfs(grid,rowIndex-1,columIndex);
        dfs(grid,rowIndex+1,columIndex);
        dfs(grid, rowIndex, columIndex-1);
        dfs(grid, rowIndex, columIndex+1);
        return;
    }
}


你可能感兴趣的:(leetcode Number of Islands)