Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- java 올림
- Math.floor()
- Math.ceil()
- 프로그래머스 숫자의 표현 java
- 자바
- 백준 16935
- java 반올림
- Arrays
- 프로그래머스 옹알이 java
- 알고리즘
- java
- 프로그래머스 연속된 수의 합 java
- 백준 4375
- 백준 14391
- mysql
- 백준 11723
- 네트워크
- 프로그래머스 도둑질 java
- 백준 17425
- java 내림
- 프로그래머스 네트워크 java
- Codility
- sort
- 백준 18290
- time complexity
- 0으로 채우기
- 코딩테스트
- Algorithm
- 백준 15661
- 백준 16927
Archives
- Today
- Total
취미처럼
[백준] 7562번 나이트의 이동 본문
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
import java.util.*;
import java.io.*;
class Node {
int y;
int x;
Node(int y, int x) {
this.y = y;
this.x = x;
}
}
public class Main {
static int l;
static int[][] map;
static boolean[][] visit;
static int[][] dr = { { -2, -1 }, { -2, 1 }, { -1, -2 }, { -1, 2 }, { 1, -2 }, { 1, 2 }, { 2, -1 }, { 2, 1 } };
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringTokenizer st;
for (int k = 0; k < t; k++) {
l = Integer.parseInt(br.readLine());
map = new int[l][l];
visit = new boolean[l][l];
st = new StringTokenizer(br.readLine());
int y = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int endY = Integer.parseInt(st.nextToken());
int endX = Integer.parseInt(st.nextToken());
bfs(y, x, endY, endX);
}
System.out.print(sb);
}
public static void bfs(int y, int x, int endY, int endX) {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(y, x));
visit[y][x] = true;
while (!q.isEmpty()) {
Node node = q.poll();
// 목표점 도달
if (node.y == endY && node.x == endX) {
sb.append(map[node.y][node.x]).append("\n");
return;
}
for (int i = 0; i < dr.length; i++) {
int ny = node.y + dr[i][0];
int nx = node.x + dr[i][1];
// 범위를 벗어나거나 방문했을 때
if (ny < 0 || ny >= l || nx < 0 || nx >= l || visit[ny][nx]) {
continue;
}
// 다음 턴 큐에 넣고
q.add(new Node(ny, nx));
// 방문처리
visit[ny][nx] = true;
// 맵에 이동 숫자 저장
map[ny][nx] = map[node.y][node.x] + 1;
}
}
}
}
'Algorithm > 백준' 카테고리의 다른 글
[백준] 13913번 숨바꼭질 4 (0) | 2021.03.11 |
---|---|
[백준] 1697번 숨바꼭질 (0) | 2021.03.11 |
[백준] 7576번 토마토 (0) | 2021.03.11 |
[백준] 2178번 미로 탐색 (0) | 2021.03.11 |
[백준] 2667번 단지번호붙이기 (0) | 2021.03.11 |
Comments