From 2368a622773736ee74f8d432f8cb891ec2f3c74c Mon Sep 17 00:00:00 2001 From: Relsola Date: Wed, 27 Dec 2023 19:23:37 +0800 Subject: [PATCH] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E6=B7=B1=E6=90=9C=E7=89=88.md=20=E6=96=B0=E5=A2=9ETS?= =?UTF-8?q?=E6=B7=B1=E5=BA=A6=E6=90=9C=E7=B4=A2=E4=BC=98=E5=85=88=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.深搜版.md | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index 43eb66e1..a4b93c3d 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -346,6 +346,46 @@ var numIslands = function (grid) { }; ``` +### TypeScript + +```TypeScript +function numIslands(grid: string[][]): number { + // 四个方向 + const dir: number[][] = [[0, 1], [1, 0], [-1, 0], [0, -1]]; + const [m, n]: [number, number] = [grid.length, grid[0].length]; + + function dfs(grid: string[][], visited: boolean[][], x: number, y: number) { + for (let i = 0; i < 4; i++) { + let nextX: number = x + dir[i][0]; + let nextY: number = y + dir[i][1]; + // 越界了,直接跳过 + if (nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) { + continue; + } + // 没有访问过同时是陆地 + if (!visited[nextX][nextY] && grid[nextX][nextY] === '1') { + visited[nextX][nextY] = true; + dfs(grid, visited, nextX, nextY); + } + } + } + + const visited: boolean[][] = Array.from({ length: m }, _ => new Array(n).fill(false)); + + let result: number = 0; + for (let i = 0; i < m; i++) { + for (let k = 0; k < n; k++) { + if (!visited[i][k] && grid[i][k] === '1') { + ++result; // 遇到没访问过的陆地,+1 + visited[i][k] = true; + dfs(grid, visited, i, k); // 将与其链接的陆地都标记上 true + } + } + } + return result; +} +``` + ### Go ```go