uva 439 Knight Moves(骑士的移动)BFS

本文介绍了一种使用广度优先搜索(BFS)算法解决骑士在棋盘上从起点到终点最少步数的问题。通过定义骑士移动的八个方向,并利用队列进行节点扩展,最终输出了从指定起点到达终点所需的最短移动步数。

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

BFS

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	
	static int[] dr = {-2,-2,-1,1,2,2,1,-1};
	static int[] dc = {-1,1,2,2,1,-1,-2,-2};
	static boolean[][] vis = new boolean[9][9];
	static int ans;
	static int start_x,start_y,end_x,end_y;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while(scan.hasNext()){
			for(int i=1;i<=8;i++){
				Arrays.fill(vis[i], false);
			}
			String start = scan.next();
			String end = scan.next();
			start_x = start.charAt(0)-'a'+1;
			start_y = 9-(start.charAt(1)-'0');
			end_x = end.charAt(0)-'a'+1;
			end_y = 9-(end.charAt(1)-'0'); 
			Queue<Node> q = new LinkedList<>();
			Node u = new Node(start_x,start_y,0);
			q.add(u);
			while(!q.isEmpty()){
				u = q.poll();
				if(u.r==end_x&&u.c==end_y){
					System.out.printf("To get from %s to %s takes %d knight moves.\n",start,end,u.d);
					break;
				}
				for(int i=0;i<8;i++){
					int r = u.r+dr[i];
					int c = u.c+dc[i];
					if(inside(r,c)){
						q.add(new Node(r,c,u.d+1));
					}
				}
			}
		}
	}
	
	public static boolean inside(int r,int c){
		return r>=1&&r<=8&&c>=1&&c<=8;
	}

	static class Node{
		int r,c,d;
		public Node(int r,int c,int d){
			this.r = r;
			this.c = c;
			this.d = d;
		}
	}
}


"Knight moves"是指国际象棋中的“马”走法,即一步可以跳过一个正方形格,然后向左、右、上或下两个方向再跳一格,形成“L”形移动。在Java中,你可以通过模拟这种规则来实现一个骑士移动函数。以下是一个简单的示例: ```java public class KnightMove { public static boolean isLegalMove(int x1, int y1, int x2, int y2, int boardSize) { // 骑士的合法移动范围:(x, y) -> (x±2, y±1)(x±1, y±2) if (Math.abs(x1 - x2) == 2 && Math.abs(y1 - y2) == 1 || Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 2) { return true; } else if (x1 >= 0 && x1 < boardSize && y1 >= 0 && y1 < boardSize && x2 >= 0 && x2 < boardSize && y2 >= 0 && y2 < boardSize) { // 确保不在边界外 return true; } return false; } public static void move(int[][] chessBoard, int startRow, int startCol, int endRow, int endCol) { if (isLegalMove(startRow, startCol, endRow, endCol, chessBoard.length)) { System.out.println("Valid knight move from (" + startRow + ", " + startCol + ") to (" + endRow + ", " + endCol + ")"); } else { System.out.println("Invalid knight move."); } } // 示例用法 public static void main(String[] args) { int[][] board = new int[8][8]; move(board, 1, 2, 6, 5); // 骑士(1, 2)移到(6, 5),这是一个合法的步骤 move(board, 0, 0, 8, 8); // 越界无效移动 } } ``` 这个`KnightMove`类包含了判断骑士是否能从一个位置移动到另一个位置的`isLegalMove`方法,以及显示移动结果的`move`方法。在`main`函数中,你可以测试不同的坐标对。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值