中国象棋之马走日

本文介绍了一个基于回溯法实现的中国象棋中马走日路径计算算法。通过递归的方式,计算从任意起点到达终点的所有可能路径数量。使用Java语言实现,并通过用户输入确定马的起始位置和目标位置。

import java.util.Scanner;
public class six_2010_2015_2017_2 {
	private final static int dx[] = {2, 1, -1, -2};
	private final static int dy[] = {1, 2, 2, 1};
	// 半个中国象棋5行9列
	private final static int X = 6;
	private final static int Y = 10;
	private static int[][] chessboard = new int[X][Y];				// 棋盘
	private final static int visited = 1;
	private final static int unvisited = 0;
	private static int count = 0;									// 记录次数
	
	
	private static void horseCount(int srcX, int srcY, int destX, int destY) {
		if(srcX < 1 || srcX > 5 || srcY < 1 || srcY > 9 || chessboard[srcX][srcY] == 1)
			return;
		if(srcX == destX && srcY == destY) {
			count++;
			return;
		}
		chessboard[srcX][srcY] = visited;
		
		for(int i = 0; i < dx.length; ++i) {
			horseCount(srcX+dx[i], srcY+dy[i], destX, destY);
		}
		
		chessboard[srcX][srcY] = unvisited;
		
	}
	
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int destX, destY;								// 马要跳到的目的地
		
		System.out.print("请输入M(在1-5之间):");
		destX = sc.nextInt();
		System.out.print("请输入N(在1-9之间):");
		destY = sc.nextInt();
		if(destX >= 1 && destX <= 5 && destY >= 1 && destY <= 9) {
			horseCount(1, 1, destX, destY);	
			System.out.println("需要走" + count + "步");
		}else {
			System.out.println("输入有误!");
		}
		
		
		sc.close();
	}
}

转载于:https://my.oschina.net/chenmoxuan/blog/1786702

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值