leetcode Number of Islands

2530 단어
제목 링크
사고방식: 광범위 우선 검색
코드
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;
    }
}


좋은 웹페이지 즐겨찾기