티스토리 뷰

https://www.acmicpc.net/problem/16236

 

16236번: 아기 상어

N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다. 아기 상어와 물고기는 모두 크기를 가

www.acmicpc.net

const fs = require("fs");
const [n, ...input] = fs
  .readFileSync("./dev/stdin")
  .toString()
  .trim()
  .split("\n");

const N = +n;
let board = input.map((v) => v.split(" ").map(Number));

const findBaby = () => {
  for (let i = 0; i < N; i++) {
    for (let j = 0; j < N; j++) {
      if (board[i][j] == 9) return [i, j];
    }
  }
};

const findFish = (loc, size) => {
  const fish = [];
  const dx = [0, 0, 1, -1];
  const dy = [1, -1, 0, 0];
  let visited = Array.from(Array(N), () => Array(N).fill(false));
  let q = [];
  q.push([loc[0], loc[1], 0]);
  visited[loc[0]][loc[1]] = true;
  while (q.length > 0) {
    const [x, y, dist] = q.shift();
    for (let i = 0; i < 4; i++) {
      const nx = x + dx[i];
      const ny = y + dy[i];
      if (nx < 0 || ny < 0 || nx >= N || ny >= N || visited[nx][ny]) continue;
      if (board[nx][ny] > size) continue;
      else if (board[nx][ny] == size) {
        visited[nx][ny] = true;
        q.push([nx, ny, dist + 1]);
      } else {
        visited[nx][ny] = true;
        q.push([nx, ny, dist + 1]);
        if (board[nx][ny] > 0) fish.push([nx, ny, dist + 1]);
      }
    }
  }

  if (fish.length == 0) process.exit(console.log(time));
  else {
    return fish.sort((a, b) => {
      if (a[2] > b[2]) return 1;
      else if (a[2] < b[2]) return -1;
      else {
        if (a[0] > b[0]) return 1;
        else if (a[0] < b[0]) return -1;
        else return a[1] - b[1];
      }
    })[0];
  }
};

let time = 0;
let size = 2;
let loc = findBaby();
let cnt = 0;
while (true) {
  const [x, y, dist] = findFish(loc, size);
  cnt++;
  board[loc[0]][loc[1]] = 0;
  board[x][y] = 9;
  loc = [x, y];
  time += dist;
  if (cnt == size) {
    size++;
    cnt = 0;
  }
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함