문제 바로가기 : https://www.acmicpc.net/problem/17086
메모리 : 176080KB
시간 : 520ms
언어 : Java 11
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static class Node {
int r, c, len;
Node(int r, int c, int len) {
this.r = r;
this.c = c;
this.len = len;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] map = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int[][] vector = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 }, { 1, 1 }, { 1, -1 }, { -1, 1 }, { -1, -1 } };
int ans = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 0) { //빈땅일때
Queue<Node> q = new LinkedList<>();
boolean[][] check = new boolean[N][M];
q.add(new Node(i, j, 0));
check[i][j] = true;
//bfs
loop: while (!q.isEmpty()) {
Node n = q.poll();
for (int k = 0; k < 8; k++) {
int x = n.r + vector[k][0];
int y = n.c + vector[k][1];
if (x >= 0 && y >= 0 && x < N && y < M && !check[x][y]) {
if (map[x][y] == 1) {
//안전거리 최댓값
ans = Math.max(ans, n.len + 1);
break loop;
}
check[x][y] = true;
q.add(new Node(x, y, n.len + 1));
}
}
}
}
}
}
System.out.println(ans);
}
}
귀여운 BFS문제! 상어가 없는 빈 땅에서 가장 가까운 상어를 찾으면 값의 최대를 찾는다.
'Algorithm' 카테고리의 다른 글
[Algo] 백준 28138 재밌는 나머지 연산 JAVA (1) | 2024.05.08 |
---|---|
[Algo] 백준 21738 얼음깨기 펭귄 JAVA (0) | 2024.05.08 |
[Algo] 백준 15686 치킨 배달 JAVA (0) | 2024.05.08 |
[Algo] 백준 3980 선발 명단 JAVA (0) | 2024.05.08 |
[Algo] 백준 11582 치킨 TOP N JAVA (0) | 2024.05.08 |