본문 바로가기

코딩테스트(백준)

[백준] 2178 : 미로탐색 -JAVA(자바) - 사좋배 공유

 


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

public class Main{

	static int dx[]= {-1,0,1,0};
	static int dy[] = {0,1,0,-1};
	static int arr[][];
	static boolean visit[][];
	static int result;
	static Queueq;
	static int sero;
	static int garo;
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		sero= sc.nextInt();
		garo=sc.nextInt();
		arr= new int[sero][garo];
		visit = new boolean[sero][garo];
		q = new LinkedList();
		sc.nextLine();
		result=0;
		for(int i=0;i<sero;i++) {
			String s= sc.nextLine();
			for(int j=0;j<garo;j++) {
				arr[i][j]=s.charAt(j)-'0';
			}
		}
		q.add(new pos(0,0,1));
		BFS();
		System.out.println(result);


	}
	private static void BFS() {
		while(!q.isEmpty()) {
			pos temp = q.poll();
			int count= temp.count;
			if(temp.x==sero-1&&temp.y==garo-1) {
				result=count;
				return;
			}
			for(int i=0;i<4;i++) {
				int rx= temp.x+dx[i];
				int ry = temp.y+dy[i];
				if(rx<0||ry<0||rx>=sero||ry>=garo) {
					continue;
				}if(arr[rx][ry]==0) {
					continue;
				}if(visit[rx][ry]==true) {
					continue;
				}if(arr[rx][ry]==1&&visit[rx][ry]==false) {
					visit[rx][ry]=true;
					q.add(new pos(rx,ry,count+1));
				}

			}
		}

	}
	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;
		}
	}

}