-
Notifications
You must be signed in to change notification settings - Fork 0
/
1697_hideAndSeek.js
142 lines (105 loc) · 2.61 KB
/
1697_hideAndSeek.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// 1697 숨바꼭질
class Queue {
constructor() {
this.list = {};
this.tail = 0;
this.head = 0;
}
enqueue(item) {
this.list[this.tail] = item;
this.tail++;
}
dequeue() {
const item = this.list[this.head];
delete this.list[this.head];
this.head++;
return item;
}
getLength() {
return this.tail - this.head;
}
}
const fs = require("fs").readFileSync("input.txt");
const [start, goal] = fs.toString().trim().split(" ").map(Number);
const visited = new Array(100001).fill().map((x) => 0);
function bfs() {
const queue = new Queue();
queue.enqueue(start);
while (queue.length !== 0) {
let cur = queue.dequeue();
// console.log("cur: ", cur);
if (cur === goal) return visited[cur];
for (let nxt of [cur + 1, cur - 1, cur * 2]) {
if (!visited[nxt]) {
if (nxt < 0 || nxt > 100001) continue;
queue.enqueue(nxt);
visited[nxt] = visited[cur] + 1;
}
}
}
}
console.log(bfs());
console.log(visited);
/*
*/
// const MAX = 10001;
// let [n, k] = input[0].split(" ").map(Number);
// let visited = new Array(MAX).fill(0);
// function bfs() {
// const queue = new Queue();
// queue.enqueue(n);
// while (queue.getLength() !== 0) {
// let cur = queue.dequeue();
// if (cur === k) {
// return visited[cur];
// }
// for (let nxt of [cur - 1, cur + 1, cur * 2]) {
// // 공간 벗어난 경우 무시
// if (nxt < 0 || nxt >= MAX) continue;
// if (visited[nxt] === 0) {
// visited[nxt] = visited[cur] + 1;
// queue.enqueue(nxt);
// }
// }
// }
// }
// console.log(bfs());
/*
*/
//dfs
// const fs = require("fs");
// const input = fs.readFileSync("input.txt").toString().trim().split(" ").map(Number);
// let [cur, tar] = input;
// let min = Math.abs(tar - cur);
// let visited = [];
// function dfs(cur, tar, mv) {
// if (mv >= min) {
// return;
// } else if (cur > tar) {
// mv = mv + (cur - tar);
// if (mv > min) {
// return;
// } else if (mv < min) min = mv;
// console.log("over, visited:", visited, " back:", cur - tar, " mv:", mv);
// return;
// } else if (cur === tar) {
// if (mv < min) min = mv;
// console.log("visited: ", visited, "mv: ", mv);
// return;
// }
// mv++;
// visited.push(cur * 2);
// dfs(cur * 2, tar, mv);
// visited.pop();
// visited.push(cur + 1);
// dfs(cur + 1, tar, mv);
// visited.pop();
// visited.push(cur - 1);
// dfs(cur - 1, tar, mv);
// visited.pop();
// }
// if (cur < tar) {
// dfs(cur, tar, 0, visited);
// }
// console.log("result: ", min);
//5 17