https://www.acmicpc.net/problem/17070
17070번: 파이프 옮기기 1
유현이가 새 집으로 이사했다. 새 집의 크기는 N×N의 격자판으로 나타낼 수 있고, 1×1크기의 정사각형 칸으로 나누어져 있다. 각각의 칸은 (r, c)로 나타낼 수 있다. 여기서 r은 행의 번호, c는 열의
www.acmicpc.net
문제
유현이가 새 집으로 이사했다. 새 집의 크기는 N×N의 격자판으로 나타낼 수 있고, 1×1크기의 정사각형 칸으로 나누어져 있다. 각각의 칸은 (r, c)로 나타낼 수 있다. 여기서 r은 행의 번호, c는 열의 번호이고, 행과 열의 번호는 1부터 시작한다. 각각의 칸은 빈 칸이거나 벽이다.
오늘은 집 수리를 위해서 파이프 하나를 옮기려고 한다. 파이프는 아래와 같은 형태이고, 2개의 연속된 칸을 차지하는 크기이다.

파이프는 회전시킬 수 있으며, 아래와 같이 3가지 방향이 가능하다.

파이프는 매우 무겁기 때문에, 유현이는 파이프를 밀어서 이동시키려고 한다. 벽에는 새로운 벽지를 발랐기 때문에, 파이프가 벽을 긁으면 안 된다. 즉, 파이프는 항상 빈 칸만 차지해야 한다.
파이프를 밀 수 있는 방향은 총 3가지가 있으며, →, ↘, ↓ 방향이다. 파이프는 밀면서 회전시킬 수 있다. 회전은 45도만 회전시킬 수 있으며, 미는 방향은 오른쪽, 아래, 또는 오른쪽 아래 대각선 방향이어야 한다.
파이프가 가로로 놓여진 경우에 가능한 이동 방법은 총 2가지, 세로로 놓여진 경우에는 2가지, 대각선 방향으로 놓여진 경우에는 3가지가 있다.
아래 그림은 파이프가 놓여진 방향에 따라서 이동할 수 있는 방법을 모두 나타낸 것이고, 꼭 빈 칸이어야 하는 곳은 색으로 표시되어져 있다.

가로

세로

대각선
가장 처음에 파이프는 (1, 1)와 (1, 2)를 차지하고 있고, 방향은 가로이다. 파이프의 한쪽 끝을 (N, N)로 이동시키는 방법의 개수를 구해보자.
입력
첫째 줄에 집의 크기 N(3 ≤ N ≤ 16)이 주어진다. 둘째 줄부터 N개의 줄에는 집의 상태가 주어진다. 빈 칸은 0, 벽은 1로 주어진다. (1, 1)과 (1, 2)는 항상 빈 칸이다.
출력
첫째 줄에 파이프의 한쪽 끝을 (N, N)으로 이동시키는 방법의 수를 출력한다. 이동시킬 수 없는 경우에는 0을 출력한다. 방법의 수는 항상 1,000,000보다 작거나 같다.
예제 입력 1
3
0 0 0
0 0 0
0 0 0
예제 출력 1
1
Solve
- 입력 범위가 작아 BFS를 활용하여 모든 경우를 탐색하는 코드로 진행하려고 하였습니다.
- 움직이는 index와 현재 방향을 queue에 [x, y dir] 형태로 넣으면서, 탐색을 하였고, x, y 인덱스가 마지막에 다다랐을 경우(x === size-1 && y === size-1) answer를 하나씩 더해주어 답을 도출했습니다.
Problem
- BFS풀이가 60%에서 시간초과가 나왔습니다.
- 풀이의 문제인지, node.js의 문제인지 알 수 없어 더 찾아봐야할 것 같습니다.
- 결국 확실하게 빠르게 풀 수 있는 dp방식의 풀이를 참고하여, 작성하였습니다. (출처 : https://velog.io/@eunseokim/BOJ-17070%EB%B2%88-%ED%8C%8C%EC%9D%B4%ED%94%84-%EC%98%AE%EA%B8%B0%EA%B8%B0-1-dp-%ED%92%80%EC%9D%B4-python)
Code
// bfs풀이코드
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
empty() {
return this.length === 0 ? 1 : 0;
}
enqueue(element) {
const newNode = new Node(element);
if (!this.head) this.head = newNode;
else this.tail.next = newNode;
this.tail = newNode;
this.length++;
}
dequeue() {
if (!this.head) return -1;
const data = this.head.data;
this.head = this.head.next;
this.length--;
return data;
}
getSize() {
return this.length;
}
front() {
if (!this.length) return -1;
return this.head.data;
}
back() {
if (!this.length) return -1;
return this.tail.data;
}
}
const input = require("fs")
.readFileSync(__dirname + "/input.txt")
.toString()
.trim()
.split("\n")
.map((el) => el.trim());
const size = +input.shift();
const map = input.map((el) => el.split(" ").map((el) => +el));
let pipeDir = 0;
// dir 0에서 가는 경우는 0, 1 →
// dir 1에서 가는 경우는 0, 1, 2 ↘
// dir 2에서 가는 경우는 1, 2 ↓
const moveIndex = [
[
[0, 1],
[1, 1],
],
[
[0, 1],
[1, 1],
[1, 0],
],
[
[1, 1],
[1, 0],
],
]; // 현재dir, 가야하는 dir, xy
let answer = 0;
const bfs = () => {
const queue = new Queue();
queue.enqueue([0, 1, pipeDir]);
while (!queue.empty()) {
const [x, y, currentDir] = queue.dequeue();
if (x === size - 1 && y === size - 1) {
answer++;
continue;
}
if (currentDir === 0) {
for (let i = 0; i < 2; i++) {
const nx = x + moveIndex[currentDir][i][0];
const ny = y + moveIndex[currentDir][i][1];
if (nx >= size || ny >= size) continue;
if (map[nx][ny] === 1) continue;
if (i === 1 && (map[nx - 1][ny] === 1 || map[nx][ny - 1] === 1))
continue;
queue.enqueue([nx, ny, i]);
}
} else if (currentDir === 1) {
for (let i = 0; i < 3; i++) {
const nx = x + moveIndex[currentDir][i][0];
const ny = y + moveIndex[currentDir][i][1];
if (nx >= size || ny >= size) continue;
if (map[nx][ny] === 1) continue;
if (i === 1 && (map[nx - 1][ny] === 1 || map[nx][ny - 1] === 1))
continue;
queue.enqueue([nx, ny, i]);
}
} else {
for (let i = 0; i < 2; i++) {
const nx = x + moveIndex[currentDir][i][0];
const ny = y + moveIndex[currentDir][i][1];
if (nx >= size || ny >= size) continue;
if (map[nx][ny] === 1) continue;
if (i === 0 && (map[nx - 1][ny] === 1 || map[nx][ny - 1] === 1))
continue;
queue.enqueue([nx, ny, i + 1]);
}
}
}
};
if (
map[size - 1][size - 1] === 1 ||
(map[size - 2][size - 1] === 1 && map[size - 1][size - 2] === 1)
) {
console.log(0);
} else {
bfs();
console.log(answer);
}
// dp 풀이코드
const input = require("fs")
.readFileSync(__dirname + "/input.txt")
.toString()
.trim()
.split("\n")
.map((el) => el.trim());
const size = +input.shift();
const map = input.map((el) => el.split(" ").map((el) => +el));
const dp = Array.from({length: 3}, () =>
Array.from({length: size}, () => Array.from({length: size}, () => 0))
);
dp[0][0][1] = 1;
for (let i = 2; i < size; i++) {
if (map[0][i] === 0) {
dp[0][0][i] = dp[0][0][i - 1];
}
}
for (let i = 1; i < size; i++) {
for (let j = 1; j < size; j++) {
if (map[i][j] === 0 && map[i][j - 1] === 0 && map[i - 1][j] === 0) {
dp[1][i][j] =
dp[0][i - 1][j - 1] + dp[1][i - 1][j - 1] + dp[2][i - 1][j - 1];
}
if (map[i][j] === 0) {
dp[0][i][j] = dp[0][i][j - 1] + dp[1][i][j - 1];
dp[2][i][j] = dp[2][i - 1][j] + dp[1][i - 1][j];
}
}
}
console.log(
dp[0][size - 1][size - 1] +
dp[1][size - 1][size - 1] +
dp[2][size - 1][size - 1]
);
'BOJ > Node.js' 카테고리의 다른 글
[BOJ / Node.js] 2559. 수열 (0) | 2023.02.18 |
---|---|
[BOJ / Node.js] 1920. 수 찾기 (0) | 2023.02.17 |
[BOJ / Node.js] 21921. 블로그 (0) | 2023.02.16 |
[BOJ / Node.js] 15666. N과 M(12) (0) | 2023.02.08 |
[BOJ / Node.js] 15663. N과 M(9) (0) | 2023.02.07 |