#include <iostream>

#include <queue>

using namespace std;

#define MAX_LINE 1000

int map[MAX_LINE][MAX_LINE] = { 0 };

int visited[MAX_LINE][MAX_LINE] = { 0 };


queue<pair<int, int>> q;

int tomatofind(int col, int row) {

int result = 0, i, j;

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

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

for (i = 0; i < row; i++) {

for (j = 0; j < col; j++) {

if (map[i][j] == 0) continue;

else if (map[i][j] == 1) {

q.push(make_pair(i, j));

visited[i][j] = 1;

}

else if (map[i][j] == -1) visited[i][j] = 1;

}

}


while (!q.empty()) {

int y = q.front().first; //행

int x = q.front().second; //열

q.pop();


for (int k = 0; k < 4; k++) {

int nx = x + dx[k];

int ny = y + dy[k];


if (nx < 0 || nx >= col || ny < 0 || ny >= row) {

continue;

}

else if (visited[ny][nx] == 0 && map[ny][nx] == 0)

{

visited[ny][nx] = visited[y][x] + 1; //!

q.push(make_pair(ny, nx));

}

}

}

for (i = 0; i < row; i++) {

for (j = 0; j < col; j++) {

if (visited[i][j] == 0)return  -1;

else if (visited[i][j] > result) result = visited[i][j];

}

}

return result - 1;

}


int main() {

int row, col, i, j;

cin >> col >> row;

for (i = 0; i < row; i++) {

for (j = 0; j < col; j++)

cin >> map[i][j];

}

cout << tomatofind(col, row);

}

'자윤이와고리즘 > Code' 카테고리의 다른 글

[백준]1934|최소공배수  (0) 2019.05.07
[백준]2609|최대공약수와최소공배수  (0) 2019.05.07
[백준]9012|괄호  (0) 2019.03.23
[백준]9372|상근이의여행  (0) 2019.03.22
[백준]1260번|DFS와BFS  (0) 2019.03.22

+ Recent posts