leetcode Number of Islands

来源:互联网 发布:网络数字电视怎么打开 编辑:程序博客网 时间:2024/05/16 04:51

题目链接

思路:
广度优先搜索

代码

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;    }}
0 0