骑士在爪哇的岩石之旅

问题描述

我正在解决以下问题:

一个方法,给定一个棋盘,棋盘上有一个骑士,在一些格子上有石头,还有一个目标位置,指示骑士是否能在不落在任何石头上的情况下到达目标,如果是,最小的数字骑士到达目标所需的移动数。该方法应该返回这样做所需的最小移动次数;否则,该方法应返回值 -1。 (如果初始位置有石头,方法返回-1;同样,如果目标位置有石头,方法返回-1。)

您可以在下面看到我迄今为止实现的代码。我处理石头的方法是改变棋盘上有石头被访问过的“坐标”,这样骑士就不能重新访问它们,从而挡住了他的路径(?)。

我的程序编译但不返回最小移动数或 -1。非常感谢解决问题的任何提示/不同方法。谢谢!!

PS:我对 Java 一窍不通,所以提前为乱七八糟的代码道歉:)

import java.util.*;

public class Knight {

    public static int numMoves( int dim,int xstart,int ystart,int xtarget,int ytarget,int[] xrock,int[] yrock )
    {
        int result = -1;

        List<Integer> knightPos = new ArrayList<>(Arrays.asList(xstart,ystart));
        int [] targetPos = {xtarget,ytarget};
        int dis = 0;

        // x and y direction,where a knight can move
        int[] dx = { -2,-1,1,2,-2,2 };
        int[] dy = { -1,1 };

        // queue for storing states of knight in board
        Vector<cell> q = new Vector<>();

        // push starting position of knight with 0 distance
        q.add(new cell(knightPos.get(xstart),knightPos.get(ystart),dis));

        cell t;
        int x,y;
        boolean[][] visit = new boolean[dim + 1][dim + 1];

        // make all cell unvisited
        for (int i = 1; i <= dim; i++) {
            for (int j = 1; j <= dim; j++) {
                visit[i][j] = false;
            }
        }

        // visit starting state
        visit[knightPos.set(0,xstart)][knightPos.set(1,ystart)] = true;

        // visit rock squares
        for (int i = 0; i < xrock.length;) {
            for (int j = 0; j < yrock.length; ++i,++j) {
                visit[knightPos.get(i)][knightPos.get(j)] = true;
            }
        }

        // loop until we have one element in queue
        while (!q.isEmpty()) {
            t = q.firstElement();
            q.remove(0);

            // if current cell is equal to target cell,// return its distance
            if (t.x == targetPos[0] && t.y == targetPos[1])
                return t.dis;

            // loop for all reachable states
            for (int i = 0; i < 8; i++) {
                x = t.x + dx[i];
                y = t.y + dy[i];

                // If reachable state is not yet visited and
                // inside board,push that state into queue
                if (isInside(x,y,dim) && !visit[x][y]) {
                    visit[x][y] = true;
                    q.add(new cell(x,dis + 1));
                }
            }
        }
        return result;
    }


    public static boolean isInside (int x,int y,int dim)
    {
        return x >= 0 && x <= dim && y >= 0 && y <= dim;
    }


    static class cell {
        int x,y;
        int dis;

        public cell(int x,int dis) {
            this.x = x;
            this.y = y;
            this.dis = dis;
        }

    }

    public static void main( String[] args )
    {

    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)