hdu1195—bfs搜索

给你两个4位的数字,对每位数字可以+1或者-1,1-1变成9,9+1变成1,相邻两位还可以交换位置,最少需要多少步可以把第一串数字改成第二串,求最少的距离。对每个数,枚举它能到11个状态,判一下重,用bfs暴搜即可。

import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;

public class hdu1195 {
    public static int fn(int a,int b,int c,int d){
        return d+c*10+b*100+a*1000;
    }
    public static int[] zhuan(int xx){
        int[] res = new int[11];
        int d = xx%10;
        int c = (xx/10)%10;
        int b = (xx/100)%10;
        int a = xx/1000;
        if (a==1){
            res[0] = fn(9,b,c,d);
        }else {
            res[0] = fn(a-1,b,c,d);
        }
        if (b==1){
            res[1] = fn(a,9,c,d);
        }else {
            res[1] = fn(a,b-1,c,d);
        }
        if (c==1){
            res[2] = fn(a,b,9,d);
        }else {
            res[2] = fn(a,b,c-1,d);
        }
        if (d==1){
            res[3] = fn(a,b,c,9);
        }else {
            res[3] = fn(a,b,c,d-1);
        }

        if (a==9){
            res[4] = fn(1,b,c,d);
        }else {
            res[4] = fn(a+1,b,c,d);
        }
        if (b==9){
            res[5] = fn(a,1,c,d);
        }else {
            res[5] = fn(a,b+1,c,d);
        }
        if (c==9){
            res[6] = fn(a,b,1,d);
        }else {
            res[6] = fn(a,b,c+1,d);
        }
        if (d==9){
            res[7] = fn(a,b,c,1);
        }else {
            res[7] = fn(a,b,c,d+1);
        }

        res[8] = fn(b,a,c,d);
        res[9] = fn(a,c,b,d);
        res[10] = fn(a,b,d,c);

        return res;
    }
    static class node implements Comparable<node>{
        int x;
        int cut;
        public node(int x,int cut){
            this.x = x;
            this.cut = cut;/*计数*/
        }
        @Override
        public int compareTo(node o) {
            return this.cut - o.cut;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            int xx = sc.nextInt();
            int yy = sc.nextInt();
            int ans = 0;
            int[] flag = new int[10000];
            flag[xx] = 1;
            node s0 = new node(xx,0);
            Queue<node> que = new PriorityQueue<node>();
            que.offer(s0);
            while(!que.isEmpty()) {
                node pre = que.poll();
                if (pre.x == yy) {
                    ans = pre.cut;
                    break;
                }else{
                    int kk = 0;
                    for (int j = 0; j < 11; j++) {
                        if (flag[zhuan(pre.x)[j]] != 1){
                            que.offer(new node(zhuan(pre.x)[j], pre.cut+1));
                            flag[zhuan(pre.x)[j]] = 1;
                        }
                    }
                }
            }
            System.out.println(ans);
        }
    }
}

 

posted @ 2025-01-25 11:20  XiaohuangTX  阅读(7)  评论(0)    收藏  举报