|
| 1 | +//https://www.acmicpc.net/problem/7576 |
| 2 | +#include <iostream> |
| 3 | +#include <vector> |
| 4 | +#include <queue> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +struct Node { |
| 8 | + int x, y; |
| 9 | +}; |
| 10 | + |
| 11 | +int M, N, answer; |
| 12 | +int arr[1001][1001]; |
| 13 | +bool visited[1001][1001]; |
| 14 | + |
| 15 | +const int dx[4] = {-1, 0, 1, 0}; |
| 16 | +const int dy[4] = {0, 1, 0, -1}; |
| 17 | + |
| 18 | +queue<pair<Node, int>> q; |
| 19 | + |
| 20 | +bool OOB(int x, int y) { |
| 21 | + return x < 0 || x >= N || y < 0 || y >= M; |
| 22 | +} |
| 23 | + |
| 24 | +void bfs() { |
| 25 | + while(!q.empty()) { |
| 26 | + pair<Node, int> now = q.front(); |
| 27 | + q.pop(); |
| 28 | + |
| 29 | + answer = max(answer, now.second); |
| 30 | + |
| 31 | + for(int dir = 0; dir < 4; dir++){ |
| 32 | + int nx = now.first.x + dx[dir]; |
| 33 | + int ny = now.first.y + dy[dir]; |
| 34 | + |
| 35 | + if (OOB(nx, ny) || visited[nx][ny] || arr[nx][ny] == -1) continue; |
| 36 | + |
| 37 | + visited[nx][ny] = true; |
| 38 | + q.push({{nx, ny}, now.second + 1}); |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +int main(){ |
| 44 | + ios::sync_with_stdio(false); |
| 45 | + cin.tie(0); cout.tie(0); |
| 46 | + |
| 47 | + cin >> M >> N; |
| 48 | + for(int i = 0; i < N; i++){ |
| 49 | + for(int j = 0; j < M; j++){ |
| 50 | + cin >> arr[i][j]; |
| 51 | + if (arr[i][j] == 1) { |
| 52 | + q.push({{i, j}, 0}); |
| 53 | + visited[i][j] = true; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + bfs(); |
| 58 | + |
| 59 | + // 만약에 방문 안 한 곳 |
| 60 | + for(int i = 0; i < N; i++){ |
| 61 | + for(int j = 0; j < M; j++){ |
| 62 | + if (!visited[i][j] && arr[i][j] != -1) { |
| 63 | + cout << -1; |
| 64 | + return 0; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + cout << answer; |
| 69 | + return 0; |
| 70 | +} |
0 commit comments