Java实现马踏棋盘算法(骑士周游问题)

该博客内容为程序实现部分的转载,但未提供具体程序相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

内容转载自程序实现部分

package Picture;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Scanner;

public class QiShi {
	private static int X=8;//棋盘的行数
	private static int Y=8;//棋盘的列数
	private static boolean visited[];
	private static boolean finished=false;
	
	//在当前位置处,搜寻下一步的可能位置,并放入list中
	public static ArrayList<Point> Next(Point p) {
		ArrayList<Point>resultArrayList=new ArrayList<Point>();
		Point p1=new Point();
		if ((p1.x = p.x - 2) >= 0 && (p1.y = p.y - 1) >= 0) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x - 1) >= 0 && (p1.y = p.y - 2) >= 0) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x + 1) < X && (p1.y = p.y - 2) >= 0) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x + 2) < X && (p1.y = p.y - 1) >= 0) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x + 2) < X && (p1.y = p.y + 1) < Y) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x + 1) < X && (p1.y = p.y + 2) < Y) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x - 1) >= 0 && (p1.y = p.y + 2) < Y) {
			resultArrayList.add(new Point(p1));
		}
		if ((p1.x = p.x - 2) >= 0 && (p1.y = p.y + 1) < Y) {
			resultArrayList.add(new Point(p1));
		}
		return resultArrayList;
	}
	//遍历棋盘
	public static void Travel(int [][]chessBoard,int row,int comlun,int step) {
		chessBoard[row][comlun]=step;
		visited[row*Y+comlun]=true;
		ArrayList<Point> nextPoints=Next(new Point(row,comlun));
		while (!nextPoints.isEmpty()) {
			Point point=nextPoints.remove(0);
			if(!visited[point.x*Y+point.y])
			{
				Travel(chessBoard, point.x, point.y, step+1);
			}
			
		}
		if(step<X*Y && !finished)
		{
			chessBoard[row][comlun]=0;
			visited[row*Y+comlun]=false;
		}
		else {
			finished=true;
		}
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		System.out.println("请输入棋盘的行数和列数");
		do {
			X=sc.nextInt();
			Y=sc.nextInt();
		} while (X<=0||Y<=0);
		System.out.println("请输入起始位置(先行后列)");
		int row,column;
		do {
			row=sc.nextInt();
			column=sc.nextInt();
		} while (row<=0||row>X||column<=0||column>Y);
	   int [][] chessBoard=new int[X][Y];
		visited=new boolean[X*Y];
		long starttime=System.currentTimeMillis();
	    Travel(chessBoard, row-1, column-1,1);
	    long endtime=System.currentTimeMillis();
	    System.out.println("共耗时:"+(endtime-starttime)+"ms");
	    for(int []rows:chessBoard)
	    {
	    	for(int columns:rows)
	    	{
	    		System.out.print(columns+"\t");
	    	}
	    	System.out.println();
	    }
	    sc.close();
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值