내풀이
#include <cstdio>
#include <queue>
using namespace std;
int a[1000][1000];
int d[1000][1000];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int main() {
int n,m;
scanf("%d %d",&n,&m);
queue<pair<int,int>> q;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
scanf("%d",&a[i][j]);
d[i][j] = -1;
if (a[i][j] == 1) {
q.push(make_pair(i,j));
d[i][j] = 0;
}
}
}
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int k=0; k<4; k++) {
int nx = x+dx[k];
int ny = y+dy[k];
if (0 <= nx && nx < n && 0 <= ny && ny < m) {
if (a[nx][ny] == 0 && d[nx][ny] == -1) {
d[nx][ny] = d[x][y] + 1;
q.push(make_pair(nx,ny));
}
}
}
}
int ans = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (ans < d[i][j]) {
ans = d[i][j];
}
}
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (a[i][j] == 0 && d[i][j] == -1) {
ans = -1;
}
}
}
printf("%d\n",ans);
return 0;
}
정답풀이
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int board[1002][1002];
int dist[1002][1002];
int n,m;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> m >> n;
queue<pair<int,int> > Q;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> board[i][j];
if(board[i][j] == 1)
Q.push({i,j});
if(board[i][j] == 0)
dist[i][j] = -1;
}
}
while(!Q.empty()){
auto cur = Q.front(); Q.pop();
for(int dir = 0; dir < 4; dir++){
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
if(dist[nx][ny] >= 0) continue;
dist[nx][ny] = dist[cur.X][cur.Y]+1;
Q.push({nx,ny});
}
}
int ans = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(dist[i][j] == -1){
cout << -1;
return 0;
}
ans = max(ans, dist[i][j]);
}
}
cout << ans;
}
'Algorithm > C++' 카테고리의 다른 글
[이코테] 미로 탈출(DFS/BFS) - 예제 5-11 (0) | 2022.06.20 |
---|---|
[이코테] 음료수 얼려먹기(DFS/BFS) - 예제 5-10 (0) | 2022.06.20 |
[백준 2178] 미로 탐색 (0) | 2022.06.14 |
[백준 2667] 단지번호붙이기 (0) | 2022.06.14 |
[백준 11724] 연결 요소의 개수 (0) | 2022.06.13 |
댓글