-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path10917.js
More file actions
54 lines (47 loc) · 1.05 KB
/
10917.js
File metadata and controls
54 lines (47 loc) · 1.05 KB
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
/*
bfs
*/
const INPUT_FILE = process.platform === 'linux' ? '/dev/stdin' : './input';
const [[dream], ...changes] = require('fs')
.readFileSync(INPUT_FILE)
.toString()
.trim()
.split('\n')
.map((line) => line.split(' ').map(Number));
const next = Array.from({ length: dream }).map(() => []);
changes.forEach(([from, to]) => {
next[from].push(to);
});
const visited = Array.from({ length: dream + 1 });
const queue = {
list: [],
front: 0,
isEmpty() {
return this.list.length - this.front === 0;
},
enqueue(value) {
this.list.push(value);
},
dequeue() {
if (this.isEmpty()) return undefined;
this.front += 1;
return this.list[this.front - 1];
},
};
queue.enqueue({ state: 1, count: 0 });
let sol = -1;
while (!queue.isEmpty()) {
const { state, count } = queue.dequeue();
if (state === dream) {
sol = count;
break;
}
if (visited[state]) {
continue;
}
visited[state] = true;
next[state].forEach((nextState) => {
queue.enqueue({ state: nextState, count: count + 1 });
});
}
console.log(sol);