-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16236.js
86 lines (73 loc) · 2.13 KB
/
16236.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const { kill } = require("process");
var readline = require("readline");
var r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
r.on("line", function (line) {
input.push(line);
}).on("close", function () {
main(input);
process.exit();
});
function main(input) {
const N = +input.shift()
let result = 0;
let currBaby
const arr = input.map((str, i) => str.split(' ').map((val, j) => {
let returnVal = +val
if (returnVal === 9) {
currBaby = [i, j]
returnVal = 0
}
return returnVal
}))
const dx = [0, -1, 1, 0]
const dy = [-1, 0, 0, 1]
function bfs(start, babySize) {
let queue = [start];
const visited = {};
let depth = -1;
while (queue.length) {
const tempQueue = [];
++depth;
for (let i = 0; i < queue.length; i++) {
const [y, x] = queue[i]
if (arr[y][x] !== 0 && arr[y][x] < babySize) {return { depth:depth, currPos: [y, x] }}
for (let j = 0; j < 4; j++) {
const [ny, nx] = [y + dy[j], x + dx[j]]
if (ny >= N || nx >= N || ny < 0 || nx < 0) continue
if (visited[`${ny}${nx}`]) continue
if (arr[ny][nx] > babySize) continue
visited[`${ny}${nx}`] = true
tempQueue.push([ny, nx])
}
}
queue = [...tempQueue.sort((a, b) => {
if(a[0] === b[0]){
return a[1] - b[1]
}
return a[0] - b[0]
})]
}
return false
}
let check = true
let cnt = 0;
let size = 2
while (check){
check = bfs(currBaby,size)
cnt++
if(typeof check === "object"){
result += check.depth
currBaby = check.currPos
arr[currBaby[0]][currBaby[1]] = 0
if(cnt === size){
cnt = 0
++size
}
}
}
console.log(result)
}