Hansel

백준_2178(BFS) 본문

알고리즘과 자료구조/BFS&DFS

백준_2178(BFS)

핑슬 2022. 2. 4. 19:32
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
static Scanner sc = new Scanner(System.in);
static int n = sc.nextInt();
static int m = sc.nextInt();
static int[][] arr = new int[100+1][100+1];
static int[][] visited = new int[100+1][100+1];
static int[][] arr2 = new int[100+1][100+1];

public static boolean check(int y,int x) {
	if(y<0 || x<0 || y>n-1 || x>m-1)return false;
	if(arr[y][x]==0)
		return false;
	if(visited[y][x]==1)
		return false;
	return true;
}

public static void main(String[] args) {
  Queue<Integer> qx = new LinkedList<Integer>();
	Queue<Integer> qy = new LinkedList<Integer>();
	for(int i=0;i<n;i++) {
		String temp = sc.next();
		for(int j=0;j<m;j++) {
			arr[i][j]=Integer.parseInt(temp.charAt(j)+"");
		}
	}
	
	qx.offer(0);qy.offer(0);arr2[0][0]=1;
	while(!qy.isEmpty()&&!qx.isEmpty()) {
		int x = qx.poll(); int y = qy.poll(); int loc = arr2[y][x];

		if(check(y-1,x)) {
			qy.offer(y-1); qx.offer(x); arr2[y-1][x] = loc+1;visited[y-1][x] = 1;
		}
		if(check(y,x+1)) {
			qy.offer(y); qx.offer(x+1); arr2[y][x+1] = loc+1;visited[y][x+1] = 1;
		}
		if(check(y+1,x)) {
			qy.offer(y+1); qx.offer(x); arr2[y+1][x] = loc+1;visited[y+1][x] = 1;
		}
		if(check(y,x-1)) {
			qy.offer(y); qx.offer(x-1); arr2[y][x-1] = loc+1;visited[y][x-1] = 1;
		}

	}

	System.out.println(arr2[n-1][m-1]);
}

}

'알고리즘과 자료구조 > BFS&DFS' 카테고리의 다른 글

백준_14502(BFS)  (0) 2022.02.11
백준_14500(DFS)  (0) 2022.02.10
백준_1260(DFS&BFS)  (0) 2022.02.04
백준_7569(BFS)  (0) 2022.02.04
백준_9663(DFS)  (0) 2022.02.04