-
boj)7562 - 나이트의 이동PS/boj 2020. 12. 10. 21:3112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import java.io.*;import java.util.*;public class boj_7562 {static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));static StringTokenizer st;static int[] dx = {2, 1, -1, -2, -2, -1, 1, 2};static int[] dy = {1, 2, 2, 1, -1, -2, -2, -1};static int t, l, nx, ny;public static void main(String[] args) throws IOException {t = Integer.parseInt(br.readLine());for (int i = 0; i < t; i++) {l = Integer.parseInt(br.readLine());st = new StringTokenizer(br.readLine());Dot start = new Dot(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0);st = new StringTokenizer(br.readLine());Dot end = new Dot(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0);System.out.println(bfs(l, start, end));}}private static int bfs(int l, Dot start, Dot end) {Queue<Dot> q = new LinkedList<>();boolean[][] v = new boolean[l][l];int result = 0;v[start.x][start.y] = true;q.offer(start);if (start.x == end.x && start.y == end.y) {return result;}while (!q.isEmpty()) {Dot now = q.poll();int day = now.d;for (int j = 0; j < 8; j++) {nx = now.x + dx[j];ny = now.y + dy[j];if (nx < 0 || nx >= l || ny < 0 || ny >= l) continue;if (nx == end.x && ny == end.y) {return day + 1;}if (!v[nx][ny]) {v[nx][ny] = true;q.offer(new Dot(nx, ny, day + 1));}}}return result;}}class Dot {int x;int y;int d;public Dot(int x, int y, int d) {this.x = x;this.y = y;this.d = d;}}
cs - BFS
- Dot 클래스에 day를 같이 넣어서 움직이게 하는 방식으로 풀이
'PS > boj' 카테고리의 다른 글
boj)2250 - 트리의 높이와 너비 (0) 2020.12.12 boj)1991 - 트리 순회 (0) 2020.12.11 boj)11723 - 집합 (0) 2020.12.09 boj)14391 - 종이 조각 (0) 2020.12.09 boj)2529 - 부등호 (0) 2020.12.08