반응형

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

 

11567번: 선진이의 겨울 왕국

첫 번째 테스트 케이스의 경우에는 (1,6) → (2,6) →  (3,6) →  (4,6) → (4,5) → (4,4) → (4,3) →  (4,2) → (4,1) → (3,1) → (2,1) → (2,2) →  (2,3) → (1,3) → (1,2) → (2,2) 의 순서로 가면 탈출이 가능하다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 빙판길을 입력받아 arr에 저장하고, visited 배열을 만들어 방문 여부를 저장합니다.

 

2. X가 있는 좌표는 미리 방문처리를 해줍니다.

 

3. bfs를 통해 이동을 하면서 r2, c2에 도착할 수 있고, 그때 해당 좌표의 visited의 값이 1이라면 YES를 출력하고, 그렇지 않다면 NO를 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
#include<string>
 
using namespace std;
 
int n, m;
string arr[500];
int visited[500][500];
int r1, c1, r2, c2;
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> n >> m;
 
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 'X') {
                visited[i][j] = 1;
            }
        }
    }
 
    cin >> r1 >> c1 >> r2 >> c2;
    r1--; r2--; c1--; c2--;
 
    queue<pair<intint>> q;
 
    q.push({ r1,c1 });
    visited[r1][c1] = 1;
 
    while (!q.empty()) {
        const int y = q.front().first;
        const int x = q.front().second;
        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 < n && xx >= 0 && xx < m) {
                if (visited[yy][xx] == 0) {
                    visited[yy][xx] = 1;
                    q.push({ yy,xx });
                }
                else if (yy == r2 && xx == c2) {
                    cout << "YES";
                    return 0;
                }
            }
        }
    }
 
    cout << "NO";
}
cs
반응형

+ Recent posts