【LeetCode热题100(50/100)】岛屿数量

题目地址: 链接

思路: 如果当前为陆地且未被访问过,则对当前路径进行 dfs(同时标记为访问过),最后统计进入最外层 dfs 的次数

js 复制代码
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
    const dfs = (x, y) => {

        isVit[x][y] = true;
        for(let i = 0; i < 4; i ++) {
            let [nx, ny] = [x + dx[i], y + dy[i]];
            if(0 <= nx && nx < n && 0 <= ny && ny < m && !isVit[nx][ny] && grid[x][y] == '1') {
                dfs(nx, ny);
            }
        }
    }
    let [n, m] = [grid.length, grid[0].length];
    let isVit = Array.from({length: n}, ()=>new Array(m).fill(false));
    let ans = 0;
    const dx = [0, 1, 0, -1];
    const dy = [1, 0, -1, 0];
    for(let i = 0; i < n; i ++) {
        for(let j = 0; j < m; j ++) {
            if(!isVit[i][j] && grid[i][j] == '1') {
                dfs(i, j);
                ans ++;
            }
        }
    }

    return ans;
};
相关推荐
阿豪学编程9 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳9 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
csdn_aspnet10 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼10 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒10 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
paeamecium11 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Book思议-12 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
SteveSenna12 小时前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
NAGNIP12 小时前
一文搞懂CNN经典架构-DenseNet!
算法·面试
道法自然|~12 小时前
BugCTF黄道十二宫
算法·密码学