题解 | #岛屿数量#

岛屿数量

https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e

import java.util.*;


public class Solution {
    /**
     * 判断岛屿数量
     * @param grid char字符型二维数组 
     * @return int整型
     */
    public int solve (char[][] grid) {
        // write code here
        int m = grid.length;
        int n = grid[0].length;
        int result = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1') {
                    result++;
                    bfs(grid, i, j);
                }
            }
        }
        return result;
    }

    public void bfs(char[][] grid, int i, int j) {
        int m = grid.length;
        int n = grid[0].length;
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{i, j});
        while(!q.isEmpty()) {
            int sz = q.size();
            for(int k = 0; k < sz; k++) {
                int[] temp = q.poll();
                int x = temp[0];
                int y = temp[1];
                if(x-1 >= 0 && grid[x-1][y] == '1') {
                    q.offer(new int[]{x-1, y});
                    grid[x-1][y] = '0';
                }
                if(y+1 < n && grid[x][y+1] == '1') {
                    q.offer(new int[]{x, y+1});
                    grid[x][y+1] = '0';
                }
                if(x+1 < m && grid[x+1][y] == '1') {
                    q.offer(new int[]{x+1, y});
                    grid[x+1][y] = '0';
                }
                if(y-1 >= 0 && grid[x][y-1] == '1') {
                    q.offer(new int[]{x, y-1});
                    grid[x][y-1] = '0';
                }
            }
        }
    }
}

全部评论

相关推荐

gcniz:一天写两千行你闹呢
点赞 评论 收藏
分享
喜欢走神的孤勇者练习时长两年半:池是池,发是发,我曾池,我现黑
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务