알고리즘/백준

[백준 1261] 알고스팟 C++

겜도리도리 2021. 10. 30. 23:52
반응형

문제

백준 1261 알고스팟 C++

 

1261번: 알고스팟

첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미

www.acmicpc.net

풀이

1. 시작점부터 bfs를 실행하여 목적지까지 도달하는 경로를 찾습니다.

2-1. 목적지에 도달하지 못했다면, 이번 bfs를 실행하는 동안 만난 벽(1)들을 빈 방(0)으로 바꿔줍니다.

2-2. 목적지에 도달했다면, 지금까지 실행했던 bfs 횟수 - 1을 출력합니다.

3. 목적지에 도달할 수 있을 때까지 1 ~ 2 과정을 반복합니다.

소스 코드

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
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
 
int dx[] = { 00-11 };
int dy[] = { -1100 };
int map[100][100];
int N, M, cnt;
bool visited[100][100];
bool Isreach = false;
 
void bfs() {
    queue<pair<intint>> q;
    q.push(make_pair(00));
    visited[0][0= true;
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        // 목적지 도달시 return
        if (x == M - 1 && y == N - 1) {
            cout << cnt;
            Isreach = true;
            return;
        }
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx >= 0 && ny >= 0 && nx < M && ny < N) {
                // 벽을 0으로 바꿔주고 방문처리
                if (!visited[ny][nx]) {
                    visited[ny][nx] = true;
                    if (map[ny][nx] == 0) {
                        q.push(make_pair(nx, ny));
                    }
                    else {
                        map[ny][nx] = 0;
                    }
                }
            }
        }
    }
    cnt++;
}
 
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> M >> N;
    string s;
    for (int i = 0; i < N; i++) {
        cin >> s;
        for (int j = 0; j < M; j++) {
            map[i][j] = s[j] - 48;
        }
    }
    while (1)
    {
        memset(visited, 0sizeof(visited));
        bfs();
        // 도달할 수 있을 때 까지 반복, 벽 허뭄
        if (Isreach)
            break;
    }
    return 0;
}
cs
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 1967] 트리의 지름 C++  (0) 2021.11.02
[백준 2573] 빙산 C++  (0) 2021.10.31
[백준 17144] 미세먼지 안녕! C++  (0) 2021.10.29
[백준 1707] 이분 그래프 C++  (0) 2021.10.26
[백준 1806] 부분합 C++  (0) 2021.10.25