반응형

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

 

4179번: 불!

입력의 첫째 줄에는 공백으로 구분된 두 정수 R과 C가 주어진다. 단, 1 ≤ R, C ≤ 1000 이다. R은 미로 행의 개수, C는 열의 개수이다. 다음 입력으로 R줄동안 각각의 미로 행이 주어진다.  각각의 문

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. queue에 불의 좌표를 먼저 넣습니다.

 

2. 지훈이의 좌표를 queue에 넣습니다.

 

3. bfs를 돌면서 불을 먼저 이동시키고 이후 지훈이를 이동시키면서 지훈이가 범위 밖으로 벗어나면 현재까지 이동한 거리를 출력합니다.

 

4. queue가 빌 때까지 지훈이가 탈출하지 못하면 IMPOSSIBLE을 출력합니다.

 

[ 소스코드 ]

 

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
#include<iostream>
#include<queue>
 
using namespace std;
 
int R, C;
char arr[1001][1001];
int visited[1001][1001];
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
 
struct node {
    int y;
    int x;
    int cur;
    int cnt;
};
 
int main()
{
    scanf("%d %d"&R, &C);
    queue<node>q;
    int r, c;
 
    for (int i = 0; i < R; i++) {
        scanf("%s"&arr[i]);
    }
 
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            if (arr[i][j] == 'F') {
                q.push({ i,j,1 });
            }
            if (arr[i][j] == 'J') {
                r = i;
                c = j;
            }
        }
    }    
 
    q.push({ r,c,0,0 });
    visited[r][c] = 1;
 
    while (!q.empty()) {
        const int y = q.front().y;
        const int x = q.front().x;
        const int cur = q.front().cur;
        const int cnt = q.front().cnt;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            const int yy = y + dy[i];
            const int xx = x + dx[i];
 
            if (yy >= 0 && yy < R && xx >= 0 && xx < C) {
                if (cur == 1) {
                    if (arr[yy][xx] == '.') {
                        arr[yy][xx] = 'F';
                        q.push({ yy,xx,1 });
                    }
                }
                else {
                    if (arr[yy][xx] == '.') {
                        if (visited[yy][xx] != 1) {
                            visited[yy][xx] = 1;
                            q.push({ yy,xx,0,cnt + 1 });
                        }
                    }
                }
            }
            else {
                if (cur == 0) {
                    printf("%d", cnt + 1);
                    return 0;
                }
            }
        }
    }
 
    printf("IMPOSSIBLE");
}
cs
반응형

+ Recent posts