【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;
};
相关推荐
吞下星星的少年·-·3 小时前
U549625 小苯的区间和疑惑(枚举,前后缀)
算法
李剑一3 小时前
到底啥是千年虫2.0?为什么量子计算能够突破公钥私钥体系?什么是后量子密码?
算法·ai编程
Techblog of HaoWANG3 小时前
具身智能机器人专题(7)大模型 / 语音 / RAG 的容器化架构与系统开发
人工智能·算法·大模型·边缘计算·具身智能
专注仿真3 小时前
仿真智能体训练(评估指标篇):探测/杀伤链时延算法详解与实战
算法·afsim智能体·afsim智能体训练·评估算法·探测时延算法·杀伤链时延算法
r_oo_ki_e_5 小时前
牛牛与切割机
java·算法
小糖学代码5 小时前
LLM系列:4.transformer算法:4.NLTK(补充)
深度学习·算法·transformer
geovindu7 小时前
python: PCA
开发语言·后端·python·算法
凯程序猿1号8 小时前
基于射线法与球面外积的WGS84电子围栏点在多边形内判定及边界容差算法
算法·电脑
budingxiaomoli8 小时前
动态规划---子序列
算法·动态规划
释厄6238 小时前
尺子必回量与劣币生良币——可证伪明的尺子性·同源可转化
大数据·算法·开源