Я пытаюсь решить задачу, которая состоит в том, чтобы получить минимальную стоимость ходов коня от источника к месту назначения на шахматной доске (8*8), и я получаю случай, который не работает... Наверное, я где-то напутал и не могу это понять.
см. изображение здесь
полный код
Я пытаюсь решить задачу, которая состоит в том, чтобы получить минимальную стоимость ходов коня от источника к месту назначения на шахматной доске (8*8), и я получаю случай, который не работает... Наверное, я где-то напутал и не могу это понять. см. изображение здесь полный код [code]import java.util.ArrayList; import java.util.List;
public class Solution { static class Position{ public int x; public int y; public Position(int x, int y) { this.x = x; this.y = y; } }
public static int solution(int src, int dest) { int min = 100000000; int depth = 0; Position source = new Position(0, 0), destination = new Position(0, 0);
int [][] board = getBoard(src, dest, source, destination);
if(arrived(source, destination)) return 0;
return solve(board, source, destination, (depth), min); } public static int[][] getBoard(int src, int dest, Position source, Position destination) { int c = 0; int [][] board = new int[8][8]; for(int i = 0; i < board.length; i++){ for(int j = 0; j < board.length; j++){ if(c == src) { board[i][j] = 1; source.x = i; source.y = j; }else if(c == dest) { board[i][j] = -1; destination.x = i; destination.y = j; }else { board[i][j] = 0; } c++; } } return board; } public static int solve(int[][] board, Position position, Position destination, int depth, int min){ if(depth > min) { return depth; }
for(Position p: sort(getPossibleMoves(board, position), destination)){ if(arrived(p,destination)) { return depth + 1; } board[p.x][p.y] = depth +2; int cost = solve(board, p, destination, (depth + 1), min); board[p.x][p.y] = 0; if(cost < min){ min = cost; } } return min; } public static List sort(List positions, Position dest) { Position temp; boolean sorted = false; while(!sorted) { sorted = true; for(int i = 0; i < positions.size() - 1; i++) { if(distance(positions.get(i), dest) > distance(positions.get(i+1), dest)) { temp = positions.get(i); positions.set(i, positions.get(i+1)); positions.set(i+1, temp); sorted = false; } } } return positions; } public static double distance(Position a, Position b) { if(a.x == b.x && a.y == b.y) return 0; return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)); } public static boolean arrived(Position src, Position dest) { return src.x == dest.x && src.y == dest.y; } public static List getPossibleMoves(int [][] board, Position current){ int [][] moves = {{1,2}, {2,1}, {-1,2}, {1,-2}, {-2,1}, {2,-1}, {-1,-2}, {-2,-1}}; List positions = new ArrayList(); for(int i = 0; i < moves.length; i++) { int x = current.x + moves[i][0]; int y = current.y + moves[i][1]; if(x >= 0 && y >= 0 && x < board.length && y < board.length && board[x][y]