Skip to content

Commit c396a4b

Browse files
committed
Feat: 배열, 연결 리스트, 스택, 큐 뱀(3190번)
1 parent aa88a14 commit c396a4b

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

Diff for: 1주차/김유경/골드4_뱀_3190.js

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
const fs = require("fs");
2+
const filePath =
3+
process.platform === "linux" ? "/dev/stdin" : `${__dirname}/input.txt`;
4+
let input = fs.readFileSync(filePath).toString().trim().split("\n");
5+
6+
const n = Number(input.shift());
7+
const k = Number(input.shift());
8+
const arr = input.map((x) => x.trim());
9+
10+
const applePosition = arr
11+
.slice(0, k)
12+
.map((x) => x.split(" ").map((x) => +x - 1));
13+
14+
const l = Number(arr[k]);
15+
16+
const countArr = arr.slice(k + 1).map((x) => x.split(" "));
17+
const countObj = Object.fromEntries(countArr);
18+
19+
// 시작시에 맨위 맨좌측에 위치
20+
const queue = [[0, 0]];
21+
22+
let body = Array.from(Array(n), () => Array(n).fill(true));
23+
24+
for (let i = 0; i < k; i++) {
25+
const [x, y] = applePosition[i];
26+
body[x][y] = "a";
27+
}
28+
29+
let dir = [0, 1];
30+
let second = 0;
31+
let currentPosition = [0, 0];
32+
33+
while (true) {
34+
second += 1;
35+
36+
// 다음칸으로 전진 이동
37+
currentPosition[0] += dir[0];
38+
currentPosition[1] += dir[1];
39+
40+
// 범위를 벗어난다면 종료
41+
if (
42+
currentPosition[0] < 0 ||
43+
currentPosition[1] < 0 ||
44+
currentPosition[0] >= n ||
45+
currentPosition[1] >= n
46+
) {
47+
break;
48+
}
49+
50+
// 몸통에 부딪힌다면 종료
51+
if (isHit(queue, currentPosition)) {
52+
break;
53+
}
54+
55+
queue.push([currentPosition[0], currentPosition[1]]);
56+
57+
const isApple = body[currentPosition[0]][currentPosition[1]] === "a";
58+
if (isApple) {
59+
// 사과가 있다면 그 칸의 사과 없어짐
60+
body[currentPosition[0]][currentPosition[1]] = true;
61+
} else {
62+
//사과가 없다면 꼬리가 위치한 칸을 비운다 -> queue의 첫번째 것을 빼준다.
63+
queue.shift();
64+
}
65+
66+
const changeDirInfo = countObj[String(second)];
67+
68+
// 방향 이동이 있다면 방향 변경
69+
if (changeDirInfo) {
70+
dir = changeDir(dir, changeDirInfo);
71+
}
72+
}
73+
74+
console.log(second);
75+
76+
function isHit(queue, current) {
77+
for (let i = 0; i < queue.length; i++) {
78+
const [x, y] = queue[i];
79+
if (x === current[0] && y === current[1]) {
80+
return true;
81+
}
82+
}
83+
84+
return false;
85+
}
86+
87+
function changeDir(currnetDir, changeDirInfo) {
88+
let result = [];
89+
const [x, y] = currnetDir;
90+
91+
if (x === 0) {
92+
if (changeDirInfo === "D") {
93+
result = [y, 0];
94+
} else {
95+
result = [-y, 0];
96+
}
97+
} else if (y === 0) {
98+
if (changeDirInfo === "D") {
99+
result = [0, -x];
100+
} else {
101+
result = [0, x];
102+
}
103+
}
104+
105+
return result;
106+
}

0 commit comments

Comments
 (0)