풀이

#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;
}

'백준 > 기타' 카테고리의 다른 글

[백준/C++] 18110번: solved.ac  (0) 2023.06.28
[백준/C++] 1780번: 종이의 개수  (0) 2023.05.22
[백준/C++] 2630번: 색종이 만들기  (0) 2023.05.22
[백준/C++] 1074번: Z  (0) 2023.05.22
[백준/C++] 1992번: 쿼드트리  (0) 2023.05.22

+ Recent posts