2178

qkrrnjswo·2023년 7월 6일
0

백준, 프로그래머스

목록 보기
25/53

1. 미로 탐색

N×M크기의 배열로 표현되는 미로가 있다.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.


2. 나만의 문제 해결

그래프 탐색 문제 -> BFS DFS 중 하나로 해결 가능,
현재 문제를 봤을 때는 BFS로 푸는 편이 바르다고 생각됨

  1. 방문을 확인하기 위한 2차원 배열 1개
  2. 이동한 횟수를 확인하기 위한 2차원 배열 1개
  3. 현재 위치에서 상하좌우 노드를 확인
    BFS
  4. 큐에 첫 번째 노드 값 넣기 0,0
  5. 이동 가능하고(노드 값 1), 방문을 하지 않았다면 큐에 넣기
  6. 큐에 노드가 없을 때까지 반복

3. code

public class Main {
	static int[][] map;
	static int n;
	static int m;
	static int[][] visit;
	static int[][] count;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		n = scanner.nextInt();
		m = scanner.nextInt();
		map = new int[n][m];
		visit = new int[n][m];
		count = new int[n][m];

		for (int i = 0; i < n; i++) {
			String s = scanner.next();
			for (int j = 0; j < m; j++) {
				map[i][j] = (int) s.charAt(j) - '0';
			}
		}

		map[0][0] = 1;
		visit[0][0] = 1;
		count[0][0] = 1;

		BFS();

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

	public static void BFS(){
		int x;
		int y;
		Queue<Integer> queue = new ArrayDeque<>(n*m);
		queue.add(0);
		queue.add(0);

		while(!queue.isEmpty()){
			x = queue.poll();
			y = queue.poll();

			//위
			if (x > 0){
				if (map[x-1][y] == 1 && visit[x-1][y] == 0){
					count[x - 1][y] = count[x][y] + 1;
					queue.add(x-1);
					queue.add(y);
					visit[x - 1][y] = 1;
				}
			}
			//아래
			if (x < n-1) {
				if (map[x+1][y] == 1 && visit[x+1][y] == 0){
					count[x + 1][y] = count[x][y] + 1;
					queue.add(x+1);
					queue.add(y);
					visit[x + 1][y] = 1;
				}
			}
			//왼쪽
			if (y > 0){
				if (map[x][y-1] == 1 && visit[x][y-1] == 0) {
					count[x][y - 1] = count[x][y] + 1;
					queue.add(x);
					queue.add(y - 1);
					visit[x][y - 1] = 1;
				}
			}
			//오른쪽
			if (y < m-1) {
				if (map[x][y+1] == 1 && visit[x][y+1] == 0) {
					count[x][y + 1] = count[x][y] + 1;
					queue.add(x);
					queue.add(y + 1);
					visit[x][y + 1] = 1;
				}
			}
		}
	}
}

0개의 댓글