【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;
};
相关推荐
I_belong_to_jesus1 小时前
C++关于分支预测的优化1
开发语言·c++·算法
Code_Solitude8 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司8 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
文丑颜不良啊9 小时前
LeetCode2821~2840题目解析
java·leetcode
YLCHUP10 小时前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
思麟呀11 小时前
背包DP(01背包+完全背包)
c++·算法
笑容掩饰我的失落12 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Pniubi13 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
꧁细听勿语情꧂14 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法