题解 | 岛屿数量

岛屿数量

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 判断岛屿数量
     * @param grid char字符型二维数组
     * @return int整型
     */
    static public int solve(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++;
                    permute(grid, i, j);
                }
            }
        }
        return count;
    }

    public static void permute(char[][] grid, int x, int y) {
        if (grid[x][y] == '0') {
            return;
        }
        grid[x][y] = '0';
        if (x + 1 < grid.length) {
            permute(grid, x + 1, y);
        }
        if (y + 1 < grid[0].length) {
            permute(grid, x, y + 1);
        }
        if (y - 1 >= 0) {
            permute(grid, x, y - 1);
        }
        if (x - 1 >= 0) {
            permute(grid, x-1, y);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务