BOJ ๋ฌธ์ œ ๋ณด๊ธฐ




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <queue>
using namespace std;

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

int box[1001][1001];
queue<pair<int, int>> q;

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

		q.pop();

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

			if (nx < 0 || ny < 0 || nx >= m || ny >= n || box[ny][nx] != 0) continue;

			box[ny][nx] = box[y][x] + 1;
			q.push({ ny, nx });
		}
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	// init & input
	int m, n;
	cin >> m >> n;

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

	//solve
	bfs(n, m);

	int cnt = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (box[i][j] == 0)
			{
				cout << -1;
				return 0;
			}

			cnt = max(cnt, box[i][j]);
		}
	}

	// ouptput
	cout << cnt - 1;

	return 0;
}


image

Leave a comment