Treasure Island
문제 복기

Last updated
문제 복기

Last updated
import java.util.*;
class TI{
int x, y;
TI(int x,int y){
this.x = x;this.y = y;
}
}
public class TreasureIsland {
public static int r;
public static int c;
public static char[][] a;
public static int[][] d;
public static int[] dx = {-1,1,0,0};
public static int[] dy = {0,0,-1,1};
public static int bfs(int x,int y) {//(0,1)
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
d[i][j] = -1;
}
}
int ans = -1;
Queue<TI> q = new LinkedList<TI>();
q.add(new TI(x,y));//(0,1)추가.
d[x][y] = 0;//시작좌표 d[x][y] = d[0][1] = 0.
while(!q.isEmpty()) {
TI cur = q.remove();
for(int i=0;i<4;i++) {
int nx = cur.x+dx[i];
int ny = cur.y+dy[i];
if(nx<0 || nx>r-1 || ny<0 || ny>c-1) continue;
if(a[nx][ny] == 'L' && d[nx][ny]==-1) {
q.add(new TI(nx,ny));
d[nx][ny] = d[cur.x][cur.y]+1;
}
}
}
for(int i=0;i<r;i++) {//디버깅용 d출력.
for(int j=0;j<c;j++) {
System.out.printf("%3d",d[i][j]);
}
System.out.println();
}
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
if(ans == -1||ans<d[i][j]) {ans = d[i][j];}
}
}
System.out.println("ans : "+ans);
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
r = sc.nextInt();
c = sc.nextInt();
a = new char[r][c];
d = new int[r][c];
sc.nextLine();
int res = -1;
for(int i=0;i<r;i++) {
String s = sc.nextLine();
for(int j=0;j<c;j++) {
a[i][j] = s.charAt(j);
if(a[i][j]=='L') {//(0,1)
if(res == -1 || res<bfs(i,j)) {
res = bfs(i,j);
}
}
}
}
//System.out.println();
System.out.println(res);
}
}