http://www.geeksforgeeks.org/minimum-steps-reach-target-knight/
Given a square chessboard of N x N size, the position of Knight and position of a target is given. We need to find out minimum steps a Knight will take to reach the target position.
Apply Dfs and a cache array (to mark visit or not) to search through all the possible ways and find the min steps.
is_outrange --is--> return infinite num
|no
|
is_visited --is--> return infinite num
|no
|
one step forward
|
|
if reach the target:
return the steps so far
else:
keep moving, try 4 directions and get minSearchSteps for 4 directions
U
D
L
R
return the min(U,D,L,R)
tricky part
infinite number for the illegal or visited location.
clear the visited mark when return.
public class Chess_Board {
private static boolean is_visited(int kx, int ky, int[][] visited) {
if (visited[kx][ky] == 1) {
return true;
}
return false;
}
private static boolean is_outrange(int kx, int ky, int size) {
if (kx < 0 || ky < 0 || kx >= size || ky >= size) {
return true;
}
return false;
}
public static void main(String[] args) {
int[][] visited_arr = new int[5][5];
int[][] board = {{0,0,0,0,1},{0,0,0,0,0},{0,0,2,0,0},{0,0,0,0,0},{0,0,0,0,0}};
System.out.println(minSearchSteps(board, 1, 2, 0, 4, visited_arr, -1));
}
private static int minSearchSteps(int[][] board, int kx, int ky, int tx, int ty, int[][] visited, int pre_steps) {
if (is_outrange(kx, ky, board.length)) {
return Integer.MAX_VALUE;
}
if (is_visited(kx, ky, visited)) {
return Integer.MAX_VALUE;
}
pre_steps += 1;
// find it
if (kx == tx && ky == ty) {
return pre_steps;
}
visited[kx][ky] = 1;
System.out.println("now kx: " + kx + " ky: " + ky + " steps: " + pre_steps);
// not found, keep moving
int leftMinSteps = minSearchSteps(board, kx - 1, ky, tx, ty, visited, pre_steps);
int rightMinSteps = minSearchSteps(board, kx + 1, ky, tx, ty, visited, pre_steps);
int upMinSteps = minSearchSteps(board, kx, ky - 1, tx, ty, visited, pre_steps);
int downMinSteps = minSearchSteps(board, kx, ky + 1, tx, ty, visited, pre_steps);
System.out.println("left: " + leftMinSteps);
System.out.println("right: " + rightMinSteps);
System.out.println("up: " + upMinSteps);
System.out.println("down: " + downMinSteps);
visited[kx][ky] = 0;
return Math.min(Math.min(leftMinSteps, rightMinSteps), Math.min(upMinSteps, downMinSteps));
}
}
网友评论