반응형
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static Queue<Point> q = new LinkedList<Point>();
static int[][] map;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int N;
static int M;
public static class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void bfs(Queue<Point> q) {
while(!q.isEmpty()) {
Point p = q.poll();
for (int i =0; i < 4; i++) {
int nextX = p.x + dx[i];
int nextY = p.y + dy[i];
if (nextX < 0 || nextY <0 || nextX >= M || nextY >=N) continue;
if (map[nextX][nextY] != 0) continue;
q.add(new Point(nextX,nextY));
map[nextX][nextY] = map[p.x][p.y]+1;
}
}
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[j][i] == 0) {
System.out.println(-1);
return;
}
max = Math.max(max, map[j][i]);
}
}
System.out.println(max-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
N = sc.nextInt();
map = new int[M][N];
visited = new boolean[M][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
map[j][i] = sc.nextInt();
if (map[j][i] == 1) {q.add(new Point(j,i));}
}
}
bfs(q);
}
}
반응형
LIST
'알고리즘 > 연습문제' 카테고리의 다른 글
백준 - 11047 동전 0 (feat. java) (0) | 2019.08.13 |
---|---|
백준 - 11399 ATM(feat. java) (0) | 2019.08.13 |
백준 2667 - 단지번호 붙이기(feat. java) (0) | 2019.08.12 |
백준 - 1697 숨바꼭질(feat. java) (0) | 2019.08.12 |
백준 2178 - 미로찾기(feat. java) (0) | 2019.08.12 |