본문 바로가기

알고리즘/백준[C++]

백준2178 숫자 재배치 c++

728x90
반응형

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

 

2178번: 미로 탐색

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

www.acmicpc.net

 

#include <iostream>
#include <queue>

using namespace std;

int N, M;

int arr[101][101];
bool visitA[101][101];

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

int main()
{
    cin >> N >> M;

    for (int i = 1; i <= N; i++)
    {
        string s;
        cin >> s;

        for (int j = 1; j <= s.length(); j++)
        {
            arr[i][j] = s[j - 1] - '0';
        }
    }

    queue<pair<pair<int, int>, int>> q;
    q.push({{1, 1}, 1});
    visitA[1][1] = true;

    while (!q.empty())
    {
        pair<pair<int, int>, int> cur = q.front();
        int y = cur.first.second;
        int x = cur.first.first;
        int dep = cur.second;
        q.pop();

        if (y == N && x == M)
        {
            std::cout << dep << endl;
            break;
        }

        for (int i = 0; i < 4; i++)
        {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (arr[ny][nx] == 1 && !visitA[ny][nx])
            {
                q.push({{nx, ny}, dep + 1});
                visitA[ny][nx] = true;
            }
        }
    }
}

정석적인 bfs문제

728x90
반응형

'알고리즘 > 백준[C++]' 카테고리의 다른 글

백준16943 숫자 재배치 c++  (0) 2023.06.23
백준 2234 성곽 c++  (0) 2022.07.27
백준 1057 토너먼트 c++  (0) 2022.07.27
백준 24444 알고리즘수업 너비우선탐색1 c++  (0) 2022.07.27
백준_2022_사다리_c++  (0) 2022.07.27