簡體   English   中英

如何用Java解決這個國際象棋騎士問題?

[英]How to solve this chess knight problem in Java?

我想使用Java解決國際象棋難題。 我編碼為Knight片段從開始字段(1; 1)移動到任何地方,除了負的x和y之外,如果所有內容都有效,則將此訪問字段放入列表中,否則返回到上一個字段。 但是它根本不起作用,這種情況永遠不會成立,它一直都是負數,並且不會返回到先前的領域,可能是什么引起了問題?

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main
{
    static Vector now;
    static Vector prev;

    static List<Vector> visited = new ArrayList<>();

    public static void main(String[] args)
    {
        now = new Vector(); // sets x = 1, y = 1
        prev = now; // also x = 1, y = 1

        visited.add(now); // we are already on (1;1)

        generate();
    }

    static void generate()
    {
        Random rand = new Random();

        for (int i = 0; i < 50; i++)
        {
            int a = rand.nextInt(8);
            move(a);

            if((isValid()) && hasNotVisited()) // if x and y > 0 , because the smallest coord is (1;1), and check is we haven't visited that field
            {
                visited.add(now);
                prev = now; // previous coord is now, then make a new step
            }
            else
            {
                now = prev; // else, return to previous coord
                // For example, we are one (3;2), we move to (1;0), that's not valid, we should move back to (3;2)
            }
        }
    }

    static void move(int a)
    {
        switch (a){
            case 0:
                now.x += 2;
                now.y++;
                break;
            case 1:
                now.x += 2;
                now.y--;
                break;
            case 2:
                now.x -= 2;
                now.y++;
                break;
            case 3:
                now.x -= 2;
                now.y--;
                break;
            case 4:
                now.y += 2;
                now.x++;
                break;
            case 5:
                now.y += 2;
                now.x--;
                break;
            case 6:
                now.y -= 2;
                now.y++;
                break;
            case 7:
                now.y -= 2;
                now.y--;
                break;
        }
    }

    static boolean hasNotVisited()
    {
        for (Vector aVisited : visited) {
            if (aVisited == now)
                return false;
        }

        return true;
    }

    static boolean isValid()
    {
        return (0 < now.x && now.x <= 10) && (0 < now.y && now.y <= 10);
    }
}

謝謝!

我想問題是您在hasNotVisited方法中使用了if (aVisited == now) 您需要if (aVisited.equals(now))代替。

  • 使用==您要檢查兩個變量是否引用Vector的同一實例。
  • 使用.equals您要檢查它是否涉及兩個具有相同屬性/值的Vector

編輯:我只是注意到Vector不會覆蓋equals 另請參見Vector源代碼 或者,您可以在hasNotVisited方法中使用(if aVisited.x == now.x && aVisited.y == now.y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM