1 条题解

  • 0
    @ 2025-10-10 15:48:07

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    //棋盘大小及起止位置 
    int n,m,s1,s2,t1,t2;
    int a[10][10];//存放棋盘
    int d[10][10];//到每个位置的最短路径 
    
    //dep:到该点的步数 
    void fun(int x,int y,int dep){
    	//如果走到这个位置的步数比假设的少(也可以防止死循环) 
    	if(dep < d[x][y]){
    		d[x][y] = dep;
    		//八个方向探测
    		if(x-1>=1&&y-2>=1) fun(x-1,y-2,dep+1); 
    		if(x-2>=1&&y-1>=1) fun(x-2,y-1,dep+1);
    		if(x-2>=1&&y+1<=m) fun(x-2,y+1,dep+1);
    		if(x-1>=1&&y+2<=m) fun(x-1,y+2,dep+1);
    		if(x+1<=n&&y+2<=m) fun(x+1,y+2,dep+1);
    		if(x+2<=n&&y+1<=m) fun(x+2,y+1,dep+1);
    		if(x+2<=n&&y-1>=1) fun(x+2,y-1,dep+1);
    		if(x+1<=n&&y-2>=1) fun(x+1,y-2,dep+1); 
    	}	
    }
    
    int main(){
    	cin>>n>>m>>s1>>s2>>t1>>t2;
    	for(int i = 1;i <= n;i++){
    		for(int j = 1;j <= m;j++){
    			d[i][j] = INT_MAX;//先设置为最大 
    		}
    	}
    	fun(s1,s2,0);
    	cout<<d[t1][t2]<<endl;
    }
    
    
    

    Java :

    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Queue;
    import java.util.Scanner;
    
    public class Main {
    	static int n;
    	static int m;
    	static int x;
    	static int y;
    	static int s;
    	static int t;
    	//记录步数
    	static int a[][] = new int[6][6];
    	//方向数组
    	static int fx[] = {-1,-2,-2,-1,1,2,2,1};
    	static int fy[] = {-2,-1,1,2,2,1,-1,-2};
    	//队列
    	static Queue<Map<String,Integer>> Q = new LinkedList<Map<String,Integer>>();
    	
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		n = sc.nextInt();
    		m = sc.nextInt();
    		x = sc.nextInt();
    		y = sc.nextInt();
    		s = sc.nextInt();
    		t = sc.nextInt();
    		//地图所有格子都是最大值
    		int i,j,oi,oj,od;
    		for(i=1;i<=n;i++) {
    			for(j=1;j<=m;j++) {
    				a[i][j] = Integer.MAX_VALUE;
    			}
    		}
    		a[x][y] = 0;
    		//now记录当前元素  next下一个元素
    		Map<String,Integer> now = new HashMap<String,Integer>();
    		Map<String,Integer> next = null;
    
    		//起始点入队
    		now.put("i",x);
    		now.put("j",y);
    		now.put("d",0);
    		Q.add(now);
    		//如果队列有元素
    		while(Q.isEmpty()==false) {
    			now = new HashMap<String,Integer>();
    			now = Q.peek();
    			Q.remove();
    			//必须符合要求才能入队
    			for(int k=0;k<8;k++) {
    				next = new HashMap<String,Integer>();
    				next.put("i", now.get("i")+fx[k]);
    				next.put("j", now.get("j")+fy[k]);
    				next.put("d", now.get("d")+1);
    				oi = next.get("i");
    				oj = next.get("j");
    				od = next.get("d");
    				if(oi>=1 && oi<=n && oj>=1 && oj<=m && od < a[oi][oj]) {
    					//说明next这个点就是下一个入队点
    					a[oi][oj] = od;
    					Q.add(next);
    				}
    			}
    		}
    		System.out.println(a[s][t]);
    		
    		sc.close();
    	}
    }
    
    
    • 1

    信息

    ID
    418
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    3
    已通过
    1
    上传者