Home 16948번(데스 나이트)
Post
Cancel

16948번(데스 나이트)

해결

  • 데스 나이트

코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int[] dr = {0,-2,-2,0,2,2};
    static int[] dc = {-2,-1,1,2,1,-1};
    static int[][] input;
    static int N;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        N = Integer.parseInt(br.readLine());
        input = new int[N+1][N+1];
        for(int[] temp : input){
            Arrays.fill(temp, -1);
        }
        st = new StringTokenizer(br.readLine());
        int r1 = Integer.parseInt(st.nextToken());
        int c1 = Integer.parseInt(st.nextToken());
        int r2 = Integer.parseInt(st.nextToken());
        int c2 = Integer.parseInt(st.nextToken());

        BFS(r1,c1);
        System.out.println(input[r2][c2]);
    }
    static void BFS(int x, int y) {
        Queue<Node> q = new LinkedList<>();
        boolean[][] visited = new boolean[N+1][N+1];
        q.add(new Node(x,y,0));
        visited[x][y] = true;
        while (!q.isEmpty()) {
            Node temp = q.poll();
            int r = temp.r;
            int c = temp.c;
            int count = temp.count;
            for(int i = 0; i < 6; i++){
                int nr = r + dr[i];
                int nc = c + dc[i];
                if(nr < 0 || nr >= N || nc < 0 || nc >= N || visited[nr][nc]) continue;
                q.add(new Node(nr,nc,count+1));
                visited[nr][nc] = true;
                input[nr][nc] = count + 1;
            }
        }
    }
}

class Node{
    int r;
    int c;
    int count;

    public Node(int r, int c, int count) {
        this.r = r;
        this.c = c;
        this.count = count;
    }
}

참고

  • 직접구현
This post is licensed under CC BY 4.0 by the author.