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
- mssql
- indexof
- 이벤트 중복 발생 현상
- 썸네일 생성
- AWS
- Filter
- fluent-ffmpeg
- math
- 객체에서 value만 가져오기
- map
- 레벨2
- MIN
- 프로그래머스
- 자바스크립트
- 리액트
- Azure Data Studio
- array
- max
- 레벨1
- reduce
- 맥에서 MSSQL
- sort
- fill
- 배열 중복 개수 구하기
- substr
- DB 백업 파일 복원
- 삼항연산자
- +연산자
- iscomposing
- AWS EBS
Archives
- Today
- Total
3은로그
백준 16948 - 데스나이트(그래프) 자바 JAVA 본문
728x90
https://www.acmicpc.net/problem/16948
16948번: 데스 나이트
게임을 좋아하는 큐브러버는 체스에서 사용할 새로운 말 "데스 나이트"를 만들었다. 데스 나이트가 있는 곳이 (r, c)라면, (r-2, c-1), (r-2, c+1), (r, c-2), (r, c+2), (r+2, c-1), (r+2, c+1)로 이동할 수 있다. 크
www.acmicpc.net
문제분석
최소이동 횟수를 구하는 문제이기 때문에 BFS로 풀 수 있다.
x,y 좌표를 Queue에 넣어야하기 때문에 Node라는 Class가 필요하다.
풀이
1. BFS로 탐색하면서 해당 칸까지의 최단거리를 방문 배열에 저장한다.
2. Queue가 빌 때까지 반복한다.
3. r2,c2 방문 배열 값을 출력한다.
코드
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class p16948_데스나이트 {
static int N; //체스판의 크기
static int r1;
static int c1;
static int r2;
static int c2;
static int[][] visited; //방문 배열
static int[][] map; //체스판 배열
static int[] X = {-2,-2,0,0,2,2};
static int[] Y = {-1,1,-2,2,-1,1};
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
N = scan.nextInt();
r1 = scan.nextInt();
c1 = scan.nextInt();
r2 = scan.nextInt();
c2 = scan.nextInt();
map = new int[N][N];
visited = new int[N][N];
for(int i = 0; i < N; i++){ //방문배열 초기화
for(int j = 0; j < N; j++){
visited[i][j] = -1;
}
}
BFS(r1,c1);
System.out.print(visited[r2][c2]);
}
static class Node {
int x, y;
public Node(int x, int y){
this.x = x;
this.y = y;
}
}
private static void BFS(int r1, int c1) {
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(r1,c1));
visited[r1][c1]++;
while (!queue.isEmpty()){
Node now_node = queue.poll();
int nowX = now_node.x;
int nowY = now_node.y;
if(nowX == r2 && nowY == c2){
break;
}
for(int i = 0; i < 6; i++){
int nextX = nowX + X[i];
int nextY = nowY + Y[i];
if(nextX < 0 || nextX >= N || nextY < 0 || nextY >= N){
continue;
}
if(visited[nextX][nextY] == -1){
queue.add(new Node(nextX,nextY));
visited[nextX][nextY] = visited[nowX][nowY] + 1;
}
}
}
}
}
'코딩테스트' 카테고리의 다른 글
[프로그래머스] Lv.0 문자열 정렬하기(1) (0) | 2023.09.05 |
---|---|
[프로그래머스] 그리디 - 큰 수 만들기 - JAVA (0) | 2023.02.13 |
BFS - 자바(JAVA) (0) | 2023.02.06 |
백준 5567 - 결혼식(그래프) 자바 JAVA (0) | 2023.02.06 |
백준 1931 - 회의실 배정 (정렬) (0) | 2023.01.09 |