알고리즘

[백준] 2178 : 미로탐색 - JAVA

멍띠 개발 2021. 11. 1. 23:46

BFS를 이용한 문제 였습니다.

Node 클래스를 만들어 x,y의 값을 저장하여 사용하며,

dx,dy 배열를 이용하여 위치를 상,하,좌,우 이동하면서 탐색 할 수 있게 하였습니다.

 

import java.util.*;

class Node{
	int x;
	int y;
	
	public Node(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	public int getX() {
		return this.x;
	}
	
	public int getY() {
		return this.y;
	}
	
}

public class 미로탈출 {
	
	static int N,M;
	static int[][] grph = new int[201][201];
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		sc.nextLine(); //Remove buffer
		for(int i=1; i<=N;i++) {
			String str = sc.nextLine();
			for(int j=1; j<=M;j++) {
				grph[i][j]= str.charAt(j-1)-'0';
			}
		}
		
		System.out.println(bfs(1,1));

	}
	
	public static int bfs(int x, int y) {
		
		int dx[] = {1,-1,0,0};
		int dy[] = {0,0,1,-1};
		
		Queue<Node> queue = new LinkedList<>();
		queue.offer(new Node(x,y));
		
		while(!queue.isEmpty()) {
			Node node = queue.poll();
			x = node.getX();
			y = node.getY();
			for(int i=0 ; i<4;i++) {
				int nx = x+dx[i];
				int ny = y+dy[i];
				if(nx<1 || nx>N  || ny<1 || ny>M) continue;
				if(grph[nx][ny]==0)continue;
				if(grph[nx][ny]==1) {
					grph[nx][ny] = grph[x][y]+1;
					queue.offer(new Node(nx,ny));
				}
			}
		}
		
		return grph[N][M];
	}
	
}

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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

 

아직 BFS와 DFS를 사용하여 문제를 풀이하는데

익숙하지 않아,

 

복습과 여러문제를 풀어서

 

익숙해 져야할거 같습니다.