[Vssue]kamacoder/0106.岛屿的周长.md
Opened this issue · 1 comments
youngyangyang04 commented
DEZREMNACUI commented
卑微的ts版本
import { createInterface } from "readline/promises";
const rl = createInterface({
input: process.stdin,
});
const readline = async () =>
(await rl[Symbol.asyncIterator]().next()).value as string;
const main = async () => {
const [M, N] = (await readline()).split(" ").map(Number);
const grid = await Promise.all(
Array.from({ length: M }, async () =>
(await readline()).split(" ").map(Number)
)
);
const visited = Array.from({ length: M }, () =>
Array.from({ length: N }, () => false)
);
const direction = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
let res = 0;
const dfs = (x: number, y: number) => {
visited[x][y] = true;
direction.forEach(([dx, dy]) => {
const nx = dx + x;
const ny = dy + y;
if (nx < 0 || nx >= M || ny < 0 || ny >= N || visited[nx][ny]) return;
if (grid[nx][ny] === 0) {
res++;
}
if (grid[nx][ny] === 1) {
dfs(nx, ny);
}
});
};
for (let i = 0; i < M; i++) {
for (let j = 0; j < N; j++) {
if (grid[i][j] === 1 && !visited[i][j]) {
dfs(i, j);
}
}
}
console.log(res);
rl.close();
};
main();