본문 바로가기
Problem Solving/Baekjoon

[백준] 26170 사과 빨리 먹기 - Graph Theory / Java

by graycode 2023. 10. 16.

 문제 링크

 

26170번: 사과 빨리 먹기

(2, 3) -> (2, 2) -> (2, 1) -> (3, 1) -> (3, 0) -> (2, 0) -> (1, 0) -> (0, 0) -> (0, 1) -> (0, 2) 가 최소 이동으로 사과 3개를 먹는 경우이다.

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

    static int[][] mat = new int[5][5];
    static boolean[][] visit = new boolean[5][5];
    static int[] dy = {-1, 1, 0, 0}, dx = {0, 0, -1, 1};
    static int min = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) mat[i][j] = read();

        dfs(read(), read(), 0, 0);

        bw.write(min != Integer.MAX_VALUE ? String.valueOf(min) : "-1");
        bw.flush();
    }

    private static void dfs(int y, int x, int depth, int cnt) {
        if (mat[y][x] == 1) cnt++;
        if (cnt == 3) {
            min = Math.min(min, depth);
            return;
        }

        visit[y][x] = true;
        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i], nx = x + dx[i];
            if (ny < 0 || ny >= 5 || nx < 0 || nx >= 5 || visit[ny][nx] || mat[ny][nx] == 131) continue;

            dfs(ny, nx, depth + 1, cnt);
        }
        visit[y][x] = false;
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글