I've been working on for a solution for the following question 'http://wcipeg.com/problems/desc/ccc10j5'. Basically, you're given a point on 2D grid (x, y). You must find the shortest path from the starting point to the ending point (which is also given).
Restrictions: You may only travel in an 'L' shape (like a knight in chess).
Although I was able to solve it, people have been telling me that there is a better way to solve it, using a tree structure (or something). Can some help me accelerate my solution.
Here's my code.
import java.util.Scanner;
public class oj{
static int steps = 0;
static int screen[][] = new int[9][9];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x, y;
x = scan.nextInt();
y = scan.nextInt();
int endx = scan.nextInt();
int endy = scan.nextInt();
for(int i = 1; i <= 8; i++)
for(int j = 1; j <= 8; j++)
screen[i][j] = 99999;
doHop(x, y, 0);
System.out.println(screen[endx][endy]);
}
public static void doHop(int x, int y, int steps){
if(x > 0 && x <= 8 && y > 0 && y <= 8 && steps < screen[x][y]){
screen[x][y] = steps;
doHop (x - 1, y + 2, steps + 1);
doHop (x - 1, y - 2, steps + 1);
doHop (x + 1, y + 2, steps + 1);
doHop (x + 1, y - 2, steps + 1);
doHop (x - 2, y + 1, steps + 1);
doHop (x - 2, y - 1, steps + 1);
doHop (x + 2, y + 1, steps + 1);
doHop (x + 2, y - 1, steps + 1);
}
}
}
Thanks in advance.