반응형

https://www.acmicpc.net/problem/14442

 

14442번: 벽 부수고 이동하기 2

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000), K(1 ≤ K ≤ 10)이 주어진다. 다음 N개의 줄에 M개의 숫자로 맵이 주어진다. (1, 1)과 (N, M)은 항상 0이라고 가정하자.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 방문 배열 visited [ 1000 ][ 1001 ][ 10 ]을 만들어 벽을 부순 개수에 따라 방문을 체크합니다.

 

2. bfs를 활용하여 도착지점에 도착하면 움직인 횟수를 출력하고 도착하지 못하면 -1을 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
 
using namespace std;
 
int N, M, K;
char arr[1000][1001];
int visited[1000][1000][10];    //부순 벽의 개수에 따라 방문을 다르게 해줌
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
struct pos {
    int y;
    int x;
    int cnt;
    int cntW;
};
 
int main()
{
    scanf("%d %d %d"&N, &M, &K);
 
    for (int i = 0; i < N; i++) {
        scanf("%s", arr[i]);
    }
 
    queue<pos> q;
    q.push({ 0,0,1,0 });
    visited[0][0][0= 1;
 
    while (!q.empty()) {
        int y = q.front().y;
        int x = q.front().x;
        int cnt = q.front().cnt;
        int cntW = q.front().cntW;
        q.pop();
 
        if (y == N - 1 && x == M - 1) {
            printf("%d", cnt);
            return 0;
        }
 
        for (int i = 0; i < 4; i++) {
            int yy = y + dy[i];
            int xx = x + dx[i];
            if (yy >= 0 && yy < N && xx >= 0 && xx < M) {
                if (arr[yy][xx] == '0' && visited[yy][xx][cntW] != 1) {    //벽이 아닐 때
                    visited[yy][xx][cntW] = 1;
                    q.push({ yy,xx,cnt + 1,cntW });
                }
                else if (arr[yy][xx] == '1' && visited[yy][xx][cntW + 1!= 1 && cntW < K) {    //벽일 때
                    visited[yy][xx][cntW + 1= 1;
                    q.push({ yy,xx,cnt + 1,cntW + 1 });
                }
            }
        }
    }
 
    printf("%d"-1);
}
cs
반응형

+ Recent posts