취미처럼

[백준] 1261번 알고스팟 본문

Algorithm/백준

[백준] 1261번 알고스팟

sirius 2021. 3. 15. 09:46
https://www.acmicpc.net/problem/1261
 

1261번: 알고스팟

첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미

www.acmicpc.net

 

import java.util.*;
import java.io.*;


public class Main {

    static int N, M;
    static int[][] map;
    static int[][] visit;

    static int[] dy = {0, 1, 0, -1};
    static int[] dx = {1, 0, -1, 0};

    static int min = Integer.MAX_VALUE;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        M = Integer.parseInt(st.nextToken());
        N = Integer.parseInt(st.nextToken());
        map = new int[N][M];
        visit = new int[N][M];
        for(int i = 0; i < N; i++) {
            String input = br.readLine();
            for(int j = 0; j < M; j++) {
                map[i][j] = input.charAt(j) - '0';
                visit[i][j] = Integer.MAX_VALUE;
            }
        }


        dijkstra();
        System.out.println(visit[N-1][M-1]);

    }

    public static void dijkstra() {
        PriorityQueue<Node> pq = new PriorityQueue<>();
        visit[0][0] = 0;
        pq.offer(new Node(0, 0, 0));
        while(!pq.isEmpty()) {
            Node node = pq.poll();

            if(node.y == N - 1 && node.x == M - 1) {
            	return;
            }


            for(int i = 0; i < 4; i++) {
                int ny = node.y + dy[i];
                int nx = node.x + dx[i];
                int nextBroken = node.brokenCnt;
                if(ny < 0 || ny >= N || nx < 0 || nx >=M) {
                	continue;
                }

                if(map[ny][nx] == 1) {
                	nextBroken++;
                }
                if(visit[ny][nx] > nextBroken) {
                    visit[ny][nx] = nextBroken;
                    pq.offer(new Node(ny, nx, nextBroken));
                }

            }
        }
    }

    static class Node implements Comparable<Node> {
        int y;
        int x;
        int brokenCnt;

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

        @Override
            public int compareTo(Node node) {
            return this.brokenCnt - node.brokenCnt;
        }
    }

}

 

 

2021.03.15 - [Algorithm/이론] - 다익스트라(Dijkstra)

 

다익스트라(Dijkstra)

다익스트라(Dijkstra) 최단경로 알고리즘 그리디 알고리즘으로 분류 - 매번 가장 비용이 적은 노드를 선택해서 반복 DFS/BFS 의 경우 모든 노드간의 가중치가 같고, 얼마나 적은 수의 노드를 거쳤는

devprogrammer.tistory.com

 

'Algorithm > 백준' 카테고리의 다른 글

[백준] 16935번 배열 돌리기 3  (0) 2021.03.15
[백준] 16927번 배열 돌리기 2  (0) 2021.03.15
[백준] 13549번 숨바꼭질3  (0) 2021.03.11
[백준] 14226번 이모티콘  (0) 2021.03.11
[백준] 13913번 숨바꼭질 4  (0) 2021.03.11
Comments