PS

BOJ 2178 : 미로탐색

lickelon 2024. 2. 27. 22:31

태그 : BFS

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net


코드

#include <bits/stdc++.h>

#define all(x) (x).begin(), (x).end()

#define INF 0x7FFFFFFF

using namespace std;

using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;

int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};

int board[102][102];
bool _visit[102][102];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n, m;
    cin >> n >> m;
    for(int i = 0; i < n; i++) {
        string s;
        cin >> s;
        for(int j = 0; j < m; j++) {
            board[i+1][j+1] = s[j] - '0';
        }
    }

    queue<pair<pii, int>> _q;
    _q.push({{1,1},1});
    _visit[1][1] = true;
    while(!_q.empty()) {
        pair<pii, int> cur = _q.front(); _q.pop();
        int x = cur.first.first;
        int y = cur.first.second;
        int d = cur.second;
        if(x == n && y == m) {
            cout << d;
            return 0;
        }
        for(int i = 0; i < 4; i++) {
            if(!_visit[x+dx[i]][y+dy[i]] && board[x+dx[i]][y+dy[i]]) {
                _q.push({{x+dx[i],y+dy[i]}, d+1});
                _visit[x+dx[i]][y+dy[i]] = 1;
            }
        }
    }

    return 0;
}

풀이

기본적인 BFS문제이다.

'PS' 카테고리의 다른 글

BOJ 15900 : 나무 탈출  (1) 2024.02.29
BOJ 1021 : 회전하는 큐  (0) 2024.02.28
BOJ 1520 : 내리막 길  (1) 2024.02.26
BOJ 1788 : 피보나치 수의 확장  (1) 2024.02.25
BOJ 2559 : 수열  (0) 2024.02.24