KnightTour(启发式可访问性

时间:2015-05-09 07:07:12

标签: java

我在编程方面不太好。有人帮我查看我的代码吗?我总是得到错误 "线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:-1"

以下是我的代码:

import java.util.Random;

public class Knight 
{
    Random rand=new Random();

public void start() 
{
    int[][] square = new int[8][8];
    int currentRow;
    int currentColumn;
    int x,y,count,tempy,tempx,lowest=0,count1=0;
    int moveNumber;
    int [] horizontal={2,1,-1,-2,-2,-1,1,2};
    int [] vertical={-1,-2,-2,-1,1,2,2,1};
    int access[  ][  ] = { { 2, 3, 4, 4, 4, 4, 3, 2 },
                        { 3, 4, 6, 6, 6, 6, 4, 3 },
                        { 4, 6, 8, 8, 8, 8, 6, 4 },
                        { 4, 6, 8, 8, 8, 8, 6, 4 },
                        { 4, 6, 8, 8, 8, 8, 6, 4 },
                        { 4, 6, 8, 8, 8, 8, 6, 4 },
                        { 3, 4, 6, 6, 6, 6, 4, 3 },
                        { 2, 3, 4, 4, 4, 4, 3, 2 } };


    for(x=0;x<8;x++)
    {
        for(y=0;y<8;y++)
        {
            square[x][y]=0;
        }
    }

    currentRow=rand.nextInt(7);
    currentColumn=rand.nextInt(7);
    tempx=currentRow;
    tempy=currentColumn;
    square[currentRow][currentColumn]=1;
    for(count=2;count<=64;count++)
    {
        for(moveNumber=0;moveNumber<8;moveNumber++)
        {
            tempx+=vertical[moveNumber];
            tempy+=horizontal[moveNumber];
            if(tempy >= 0 && tempy < 8 && tempx >= 0 && tempx < 8 && square[tempx][tempy]==0 && square[tempx][tempy]==0)
            {
                if(access[tempx][tempy]<access[currentRow][currentColumn])
                {
                    lowest=moveNumber;
                    tempx-=vertical[moveNumber];
                    tempy-=horizontal[moveNumber];
                }
            }
            else
            {
                tempx-=vertical[moveNumber];
                tempy-=horizontal[moveNumber];
            }
        }
        currentRow+=vertical[lowest];
        currentColumn+=horizontal[lowest];
        tempx=currentRow;
        tempy=currentColumn;
        square[currentRow][currentColumn]=count;
        count1++;
    }

    System.out.printf("The tour ended with %d moves\n \t0\t1\t2\t3\t4\t5\t6\t7\n",count1+1);    
    for(x=0;x<8;x++)
    {
        System.out.printf("%d\t", x);
        for(y=0;y<8;y++)
        {
            System.out.printf("%d\t",square[x][y]);
        }
        System.out.println();
    }   
  }
}

public class KnightTesta 
{
    public static void main(String[] args) 
    {
        Knight test=new Knight();
        test.start();
    }    
}

请帮助我修改代码,因为我也能做到正确。如果我没有启发式解决方案,我可以正确地获取代码(意味着我无法完成64个游览)。

谢谢,非常感谢,希望你们能够理解我的代码,因为我不擅长编程T ^ T.

0 个答案:

没有答案