티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js)백준 13460번: 구슬 탈출 2 (0) | 2022.07.12 |
---|---|
Node.js)백준 2638번: 치즈 (0) | 2022.07.10 |
Node.js) 백준 12865번: 평범한 배낭 (0) | 2022.07.04 |
Node.js)백준 4781번: 사탕 가게 (0) | 2022.07.04 |
Node.js)백준 4811번: 알약 (0) | 2022.07.04 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 다이나밍프로그래밍
- MySQL
- 다이나믹프로그래밍
- DB 생성
- node.js
- 투포인터
- 개발자면접
- 투포인터 연습
- 면접비
- create databases;
- create db
- 서버개발
- 로드나인
- 동적프로그래밍
- BFS
- 그래프
- 서버점검
- MOD
- 면접질문
- 은둔청년체험
- 롱베케이션
- 최소공통조상
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함