본문 바로가기

코딩테스트(백준)

[백준] 2589 : 보물섬 -JAVA(자바) - 사좋배 공유


import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

	//4방 탐색중에 1곳만 되는곳.
	//보물섬
	static int dx[]= {1,0,-1,0};
	static int dy[]= {0,1,0,-1};
	static char[][] arr;
	static Queueq;
	static int sizex;
	static int sizey;
	static int result;
	public static void main(String[] args) {
		Scanner sc= new Scanner(System.in);
		sizex= sc.nextInt();
		sizey= sc.nextInt();
		sc.nextLine();
		result=0;
		q=new LinkedList();
		arr = new char[sizex][sizey];
		int max=Integer.MIN_VALUE;
		
		for(int i=0;i<sizex;i++) {
			String s = sc.nextLine();
			for(int j=0;j<sizey;j++) {
				arr[i][j]=s.charAt(j);
			}
		}
		//Q에 계속 넣기
		for(int i=0;i<sizex;i++) {
			for(int j=0;j<sizey;j++) {
				if(arr[i][j]=='L') {
					BFS(i,j);
					if(result>max) {
						max=result;
					}
					result=0;
				}
			}
		}
		System.out.println(max);
	}
	
	private static void BFS(int i,int j) {
		boolean visit[][] =new boolean[sizex][sizey];
		q.add(new pos(i,j,0));
		while(!q.isEmpty()) {
			pos temp = q.poll();
			int x= temp.x;
			int y= temp.y;
			int count=temp.count;
			result=count;
			visit[x][y]=true;
			for(int t=0;t<4;t++) {
				int rx = x+dx[t];
				int ry= y+dy[t];
				if(rx<0||ry<0||rx>=sizex||ry>=sizey) {
					continue;
				}if(visit[rx][ry]==true||arr[rx][ry]=='W') {
					continue;
				}if(arr[rx][ry]=='L'&&visit[rx][ry]==false) {
					visit[rx][ry]=true;
					q.add(new pos(rx,ry,count+1));
				}
			}
		}
		
		
	}
	private static class pos {
		int x;
		int y;
		int count;
		pos(int x,int y,int count){
			this.x=x;
			this.y=y;
			this.count=count;
		}
	}
}