DFS 解题
- 首先看是否需要遍历所有节点,例如遍历二维数组就两层循环
- 根据结果满足的条件进行递归
- dfs 递归函数找到退出递归的判断条件
- 标记成已到达防止循环
根据题意不同方向去 dfs
var numIslands = function(grid) {const col = grid[0].length;const row = grid.length;let count = 0;const dfs = (i, j) => {if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] === '0') returngrid[i][j] = '0';dfs(i, j + 1) || dfs(i, j - 1) || dfs(i + 1, j) || dfs(i - 1, j);}for(let i = 0; i < row; i++) {for(let j = 0; j < col; j++) {if (grid[i][j] === '1') {count++;dfs(i, j);}}}return count;};
BFS 解题
首先看是否需要遍历所有节点,例如遍历二维数组就两层循环
- 定义队列
- 根据结果满足的条件进行迭代
- 队列先推入节点
- 遍历队列的长度
- 取出队列值
- 找到边界直接退出,无需标记和 push 队列
- 根据题意不同方向去标记和 push 队列
var numIslands = function(grid) {const col = grid[0].length;const row = grid.length;let count = 0;let queue = [];const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];for(let i = 0; i < row; i++) {for(let j = 0; j < col; j++) {if (grid[i][j] === '1') {count++;grid[i][j] = '0';queue.push([i, j]);while(queue.length) {const cur = queue.shift();for(const dir of dirs) {const x = cur[0] + dir[0];const y = cur[1] + dir[1];if (x < 0 || x >= row || y < 0 || y >= col || grid[x][y] === '0') continuegrid[x][y] = '0';queue.push([x, y]);}}}}}return count;};
