-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBaekjoon2589.java
101 lines (79 loc) · 2.71 KB
/
Baekjoon2589.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package Algorithms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* https://www.acmicpc.net/problem/2589
* 백준 2589번 보물찾기
*/
public class Baekjoon2589 {
private static int[][] map;
private static int[][] visited;
private static int[] dx = {1, 0, -1, 0};
private static int[] dy = {0, 1, 0, -1};
private static int maxLength = 0;
private static int N, M;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int[N][M];
for (int i = 0; i < N; i++) {
String str = br.readLine();
for (int j = 0; j < M; j++) {
map[i][j] = str.charAt(j) == 'L' ? 1 : 0;
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
visited = new int[N][M];
initVisited();
bfs(i, j);
}
}
}
System.out.println(maxLength);
}
private static void initVisited() {
for (int i = 0; i < visited.length; i++) {
Arrays.fill(visited[i], Integer.MAX_VALUE);
}
}
private static void bfs(int x, int y) {
Queue<Node> queue = new LinkedList<>();
visited[x][y] = 0;
queue.add(new Node(x, y));
while (!queue.isEmpty()) {
Node current = queue.poll();
for (int i = 0; i < 4; i++) {
int nextX = current.x + dx[i];
int nextY = current.y + dy[i];
if (nextX < 0 || nextY < 0 || nextX >= N || nextY >= M) continue;
if (map[nextX][nextY] == 0) continue;
if (visited[nextX][nextY] > visited[current.x][current.y] + 1) {
visited[nextX][nextY] = visited[current.x][current.y] + 1;
queue.offer(new Node(nextX, nextY));
}
}
}
for (int i = 0; i < visited.length; i++) {
for (int j = 0; j < visited[0].length; j++) {
if (visited[i][j] == Integer.MAX_VALUE) continue;
maxLength = Math.max(visited[i][j], maxLength);
}
}
}
private static class Node {
int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}