알고리즘 공부

백준 보물섬(복습)

컴퓨터과학 2023. 11. 9. 21:42

https://www.acmicpc.net/problem/2589

 

2589번: 보물섬

보물섬 지도를 발견한 후크 선장은 보물을 찾아나섰다. 보물섬 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 각 칸은 육지(L)나 바다(W)로 표시되어 있다. 이 지도에서

www.acmicpc.net

쉬운 bfs 문제입니다.

import java.util.*;

import java.lang.*;
import java.io.*;
public class Main {
	private int i;
	private int j;
	private int cnt=0;
	public Main() {
		
	}
	public Main(int i, int j,int cnt) {
		this.i=i;
		this.j=j;
		this.cnt=cnt;
	}
	public void I(int i) {
		this.i=i;
	}
	public int I() {
		return this.i;
	}
	public void J(int j) {
		this.j=j;
	}
	public int J() {
		return this.j;
	}
	public int CNT() {
		return this.cnt;
	}

	public static void main(String[] args) throws Exception {
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		int m=scan.nextInt();
		scan.nextLine();
		
		char maps[][]=new char[n][m];
		boolean bCheck[][]=new boolean[n][m];
		boolean intbCheck[][]=new boolean[n][m];
		
		for(int i=0;i<n;i++) {
			String tmp =scan.nextLine();
			for(int j=0;j<tmp.length();j++) {
				char tmpc=tmp.charAt(j);
				maps[i][j]=tmpc;
				if(tmpc=='W') {
					bCheck[i][j]=true;
					intbCheck[i][j]=true;
				}else {
					bCheck[i][j]=false;
					intbCheck[i][j]=false;
				}
			}
		}
		
		int diri[]= {1,-1,0,0};
		int dirj[]= {0,0,1,-1};
		Queue <Main> q=new LinkedList<>();
		
		int maxs=0;
		
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				int gcnt=0;
				if(maps[i][j]=='L'&&bCheck[i][j] == false) {
					q.add(new Main(i,j,0));
					bCheck[i][j]=true;
					while(!q.isEmpty()) {
						Main start=q.peek();
						q.poll();
						
						for(int z=0;z<4;z++) {
							int tmpDiri=start.I()+diri[z];
							int tmpDirj=start.J()+dirj[z];
							if(tmpDiri==-1||tmpDirj==-1||tmpDiri>=n||tmpDirj>=m) {
								continue;
							}
							if(bCheck[tmpDiri][tmpDirj]==true) {
								
								continue;
							}
							gcnt=Math.max(gcnt, start.CNT()+1);
							q.add(new Main(tmpDiri,tmpDirj, start.CNT()+1 ));
							bCheck[tmpDiri][tmpDirj]=true;
						}
					}
				}
				maxs=Math.max(maxs, gcnt);
				for(int z=0;z<n;z++) {
					for(int t=0;t<m;t++) {
						if(intbCheck[z][t]==true) {
							bCheck[z][t]=true;
						}else {
							bCheck[z][t]=false;
						}
					}
				}
			}
		}
		System.out.println(maxs);
	}
}