백준/기타

[백준/C++] 14940번: 쉬운 최단거리

Koalitsiya 2023. 6. 28. 14:12

 

 

풀이

#include <iostream>
#include <queue>

using namespace std;

int n, m;
int arr[1001][1001];
bool isVisited[1001][1001];

int dirX[4] = { 0, 1, 0, -1 };
int dirY[4] = { 1, 0, -1, 0 };

queue<pair<int, int>> q;

void bfs() {
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();

        for (int i = 0; i < 4; i++) {
            int curX = x + dirX[i];
            int curY = y + dirY[i];

            if (curX < 0 || curX >= n || curY < 0 || curY >= m) continue;
            if (!isVisited[curX][curY]) {
                arr[curX][curY] = arr[x][y] + 1;
                isVisited[curX][curY] = true;
                q.push({ curX, curY });
            }
        }
    }
}

int main() {
    cin >> n >> m;

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            cin >> arr[i][j];
            if (arr[i][j] == 2) {
                arr[i][j] = 0;
                q.push({ i, j });
                isVisited[i][j] = true;
            }
            if (arr[i][j] == 0)
                isVisited[i][j] = true;
        }

    bfs();

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (!isVisited[i][j])
                cout << "-1 ";
            else
                cout << arr[i][j] << ' ';
        }
        cout << '\n';
    }

    return 0;
}