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

 

2665번: 미로만들기

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

www.acmicpc.net

 

다이크스트라를 이해하고 잇어야 쉽게 풀었겟네요.

 

한 5일정도 풀다가 더이상 안풀려서 대학때 배운 다이크스트라 다시 보니 좀 이해가 되네요 ㅠ 

으휴 ㅠ 다음에 비슷한문제로 좀 풀어봐야겟네요 ㅠ 

import java.util.*;

public class Main {
    private int x;
    private int y;

    public Main(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.nextLine(); 

        int[] dx = {1, -1, 0, 0};
        int[] dy = {0, 0, 1, -1};
        int[][] maps = new int[n][n];
        int[][] dist = new int[n][n];

        for (int i = 0; i < n; i++) {
            String tmp = scan.nextLine();
            for (int j = 0; j < tmp.length(); j++) {
                maps[i][j] = tmp.charAt(j) - '0';
                dist[i][j] = -1;
            }
        }

        Queue<Main> queue = new LinkedList<>();
        queue.add(new Main(0, 0));
        dist[0][0] = 0; 

        while (!queue.isEmpty()) {
            Main current = queue.poll();

            for (int i = 0; i < 4; i++) {
                int tmpDiri = current.getX() + dx[i];
                int tmpDirj = current.getY() + dy[i];

                if (tmpDiri < 0 || tmpDirj < 0 || tmpDiri >= n || tmpDirj >= n) {
                	continue; 
                } 

                int nextDist = dist[current.getX()][current.getY()];
                if (maps[tmpDiri][tmpDirj] == 0) {
                	nextDist += 1; 
                }

                if (dist[tmpDiri][tmpDirj] == -1 || dist[tmpDiri][tmpDirj] > nextDist) {
                    dist[tmpDiri][tmpDirj] = nextDist;
                    queue.add(new Main(tmpDiri, tmpDirj));
                }
            }
        }

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

'알고리즘 공부' 카테고리의 다른 글

백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11
백준 괄호의 값  (1) 2024.01.24
백준 톱니바퀴  (0) 2024.01.17
백준 숨바꼭질4  (0) 2024.01.12

+ Recent posts