leetcode: 200.岛屿数量(图搜索)

链接:https://leetcode-cn.com/problems/number-of-islands/

DFS、BFS都行,这里是bfs

class Solution {
    public int numIslands(char[][] grid) {
        int m = grid.length;
        if(m==0)
            return 0;
        int n = grid[0].length;
        int dx[] = {0,1,0,-1};
        int dy[] = {1,0,-1,0};
        int ans = 0;
        for(int i = 0;i<m;i++)
        {
            for(int j = 0;j<n;j++)
            {
                if(grid[i][j]=='1')
                {
                    Queue<Integer> q = new LinkedList();
                    q.add(i*n+j);
                    grid[i][j] = '0';
                    while(!q.isEmpty())
                    {
                        int curr = q.poll();
                        int ii = curr/n;    
                        int jj = curr%n;
                        for(int k = 0;k<4;k++)
                        {
                            if(jj+dx[k]>=0&&jj+dx[k]<n&&ii+dy[k]>=0&&ii+dy[k]<m&&grid[ii+dy[k]][jj+dx[k]]=='1')
                            {
                                grid[ii+dy[k]][jj+dx[k]]='0';
                                int temp = (ii+dy[k])*n+jj+dx[k];
                                q.add(temp);
                            }
                        }
                       
                    }
                    ans++;
                }
            }
        }
        return ans;
    }
}

你可能感兴趣的:(leetcode,leetcode,bfs,java)