fork download
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4. int a[1000][1000];
  5. int d[1000][1000];
  6. int dx[] = { 0,0,1,-1 };
  7. int dy[] = { 1,-1,0,0 };
  8. int main() {
  9. int m, n;
  10. cin >> m >> n;
  11. queue<pair<int, int>> q;
  12. for (int i = 0; i < n; i++) {
  13. for (int j = 0; j < m; j++) {
  14. cin >> a[i][j];
  15. d[i][j] = -1;
  16. if (a[i][j] == 1) {
  17. q.push(make_pair(i, j));
  18. d[i][j] = 0; //이미 익어있는 것이므로 날짜증가X
  19. }
  20. }
  21. }
  22. while (!q.empty()) {
  23. int x = q.front().first;
  24. int y = q.front().second;
  25. q.pop();
  26. for (int k = 0; k < 4; k++) {
  27. int nx = x + dx[k];
  28. int ny = y + dy[k];
  29. if (nx >= 0 && nx < n&&ny >= 0 && ny < m) {
  30. if (a[nx][ny] == 0 && d[nx][ny] == -1) {
  31. d[nx][ny] = d[x][y] + 1;
  32. q.push(make_pair(nx, ny));
  33. }
  34. }
  35. }
  36. }
  37. int ans = 0;
  38. for (int i = 0; i < n; i++) {
  39. for (int j = 0; j < m; j++) {
  40. if (ans < d[i][j])
  41. ans = d[i][j];
  42. else if (a[i][j] == 0 && d[i][j] == -1)
  43. ans = -1;
  44. }
  45. }
  46.  
  47. cout << ans << '\n';
  48. return 0;
  49. }
Success #stdin #stdout 0s 4576KB
stdin
3 3

0 -1 -1

-1 -1 0

0 -1 1
stdout
0