반응형
05-14 05:47
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[백준] 16928번 : 뱀과 사다리 게임 본문

Programming/백준

[백준] 16928번 : 뱀과 사다리 게임

조용한고라니 2021. 4. 8. 01:28
반응형
 

16928번: 뱀과 사다리 게임

첫째 줄에 게임판에 있는 사다리의 수 N(1 ≤ N ≤ 15)과 뱀의 수 M(1 ≤ M ≤ 15)이 주어진다. 둘째 줄부터 N개의 줄에는 사다리의 정보를 의미하는 x, y (x < y)가 주어진다. x번 칸에 도착하면, y번 칸으

www.acmicpc.net


[Dijkstra]

BFS로 풀어보았으나 풀다보니 다익스트라 알고리즘이 더 풀기 쉬울 것 같아서 급히 방향을 바꾸어서 풀었다.

 

map[ ]이라는 배열을 만들어서 i번 째 원소의 값은 i로 초기화한다. 그리고 n, m만큼 뱀과 사다리의 정보를 받아 해당 map[ i ]의 값을 바꾸고 다익스트라 알고리즘을 수행하면 된다.

# Code </>

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    static class Point{
        int x, m;
        public Point(int xx, int move){
            x=xx;
            m=move;
        }
    }
    static final int INF = 1000000000;
    static int[] map = new int[101], move = new int[101];

    static int Dijkstra(){
        Queue<Point> Q = new PriorityQueue<>((a, b) -> a.m - b.m);

        move[1] = 0;
        Q.add(new Point(1, 0));

        while(!Q.isEmpty()){
            Point p = Q.poll();
            int cur = p.x;
            int m = p.m;

            if(move[cur] < m) continue;

            for(int i=1; i<7; i++){
                int next = cur + i;

                if(next > 100) continue;

                if(move[ map[next] ] > m+1) {
                    move[map[next]] = move[cur] + 1;
                    Q.add(new Point(map[next], m + 1));
                }
            }
        }
        return move[100];
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        for(int i=1; i<=100; i++) {
            map[i] = i;
            move[i] = INF;
        }

        for(int i=0; i<n; i++){
            st = new StringTokenizer(br.readLine());

            int target = Integer.parseInt(st.nextToken());
            int dest = Integer.parseInt(st.nextToken());

            map[target] = dest;
        }

        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());

            int target = Integer.parseInt(st.nextToken());
            int dest = Integer.parseInt(st.nextToken());

            map[target] = dest;
        }

        System.out.println(Dijkstra());
    }
}
반응형
Comments