티스토리 뷰

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
#include <iostream>
#include <queue>
#define MAX 1001
using namespace std;
 
char map[MAX][MAX];
 
struct point {
    int row, col;
    bool isBroken; // 벽 부쉈으면 true
    int length; // 이동 거리
};
 
int BFS(int rowSize, int colSize) {
    int moveDir[4][2= { { 10 },{ -10 },{ 01 },{ 0-1 } };
    bool visit[MAX][MAX][2= { false, };
    queue<struct point> q;
    q.push({00false1});
    visit[0][0][0= true;
    visit[0][0][1= true;
 
    while (!q.empty()) {
        struct point now = q.front();
        q.pop();
 
// 도착점에 도착한 경우
        if (now.row == rowSize - 1 && now.col == colSize - 1) {
            return now.length;
        }
        
        for (int i = 0; i < 4; i++) {
            int newRow = now.row + moveDir[i][0];
            int newCol = now.col + moveDir[i][1];
            if (newRow < 0 || newRow >= rowSize || newCol < 0 || newCol >= colSize) continue;
            if (visit[newRow][newCol][now.isBroken] == truecontinue;
            visit[newRow][newCol][now.isBroken] = true;
            if (map[newRow][newCol] == '0') { // 갈 수 있는 길
                q.push({newRow, newCol, now.isBroken, now.length + 1});
            }else if (map[newRow][newCol] == '1' && now.isBroken == false) {// 벽 안 부순 경우
                q.push({newRow, newCol, true, now.length + 1});
            }
        }
    }
 
    return -1; // 도착점에 도착하지 못한 경우
}
 
int main() {
    int rowSize, colSize;
    cin >> rowSize >> colSize;
    for (int i = 0; i < rowSize; i++) {
        cin >> map[i];
    }
 
    cout << BFS(rowSize, colSize);
}
cs
 
 
 
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
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
글 보관함