youngyangyang04 / leetcode-master-comment

用来做评论区
0 stars 0 forks source link

[Vssue]kamacoder/0106.岛屿的周长.md #200

Open youngyangyang04 opened 1 month ago

youngyangyang04 commented 1 month ago

https://www.programmercarl.com/kamacoder/0106.%E5%B2%9B%E5%B1%BF%E7%9A%84%E5%91%A8%E9%95%BF.html

DEZREMNACUI commented 1 month ago

卑微的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();