728x90
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class algo_1600_김어진 {
static int N;
static int M;
static int[] hx= new int[] {-1,-2,-2,-1,1,2,2,1};
static int[] hy= new int[] {-2,-1,1,2,2,1,-1,-2};
static int[] dx= new int[] {-1,0,1,0};
static int[] dy= new int[] {0,1,0,-1};
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int answer=-1;
st = new StringTokenizer(br.readLine()," ");
int horseJump = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine()," ");
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
int[][] board = new int[N][M];
boolean[][] check = new boolean[N][M];
// 점프 한 개수만큼 배열 ex) 말 점프 안하고, 말 점프 한번, 말 점프 2번
boolean[][][] visited = new boolean[N][M][horseJump+1];
for (int i = 0; i < N; i++) {
board[i]=Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
Queue<Jump> q = new LinkedList<>();
q.add(new Jump(0,0,0,0));
visited[0][0][0]=true;
while(!q.isEmpty()) {
Jump pos = q.poll();
int x = pos.x;
int y = pos.y;
int cnt = pos.cnt;
int jump = pos.jump;
if(x==N-1 && y==M-1) {
answer=cnt;
break;
}
// 4방 탐색
for (int i = 0; i < 4; i++) {
int nx = x+ dx[i];
int ny = y+dy[i];
if(nx>=0 && nx < N && ny>=0 && ny < M && !visited[nx][ny][jump] && board[nx][ny]==0) {
q.add(new Jump(nx,ny,cnt+1,jump));
visited[nx][ny][jump]=true;
}
}
//말 점프 탐색
for (int i = 0; i < 8; i++) {
int nx = x + hx[i];
int ny = y + hy[i];
if(nx>=0 && nx < N && ny>=0 && ny < M &&jump<horseJump && board[nx][ny]==0 && !visited[nx][ny][jump+1]) {
q.add(new Jump(nx,ny,cnt+1,jump+1));
visited[nx][ny][jump+1]=true;
}
}
}
System.out.println(answer);
}
}
class Jump{
int x;
int y;
int cnt;
int jump;
public Jump(int x, int y, int cnt, int jump) {
super();
this.x = x;
this.y = y;
this.cnt = cnt;
this.jump = jump;
}
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
백준 14502 연구소 (자바) (0) | 2021.09.17 |
---|---|
백준 9205 맥주 마시면서 걸어가기 (자바) (0) | 2021.09.16 |
백준 1149 RGB거리 (자바) (0) | 2021.09.14 |
백준 1463 1로 만들기 (자바) (0) | 2021.09.14 |
백준 16236 아기 상어 (자바) (0) | 2021.08.25 |