蓝桥杯_卡片换位 java

这是一个关于简化版华容道游戏的编程挑战,目标是通过广度优先搜索(BFS)算法找到使关羽和张飞交换位置所需的最小步数。程序接收当前局面的字符串输入,然后通过BFS遍历所有可能的状态,最终输出最小步数。

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

题目描述

你玩过华容道的游戏吗?

这是个类似的,但更简单的游戏。

看下面 3 x 2 的格子

+---+---+---+

| A | * | * |

+---+---+---+

| B | | * |

+---+---+---+

在其中放 5 张牌,其中 A 代表关羽,B 代表张飞,* 代表士兵。

还有个格子是空着的。

你可以把一张牌移动到相邻的空格中去(对角不算相邻)。

游戏的目标是:关羽和张飞交换位置,其它的牌随便在哪里都可以。

输入描述

输入两行 6 个字符表示当前的局面

输出描述

一个整数,表示最少多少步,才能把 A B 换位(其它牌位置随意)

输入输出样例

示例
输入
* A
**B
输出
17

运行限制

  • 最大运行时间:1s

  • 最大运行内存: 256M

代码:

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

import javax.sound.midi.Soundbank;

public class 卡片换位 {

    static int[] dir = { -3, -1, 1, 3 };
    static int step = 0;// 步数

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.nextLine();
        String str2 = scanner.nextLine();
        // String str = str1 + str2;
        String str = str1.concat(str2);

        // 获取 A 和 B 的位置
        int Aindex = str.indexOf('A');
        int Bindex = str.indexOf('B');

        bfs(str, Aindex, Bindex);
    }

    private static void bfs(String str, int Aindex, int Bindex) {
        Queue<String> queue = new LinkedList<>();
        HashSet<String> set = new HashSet<>();//set用于去重
        queue.offer(str);
        set.add(str);
        while (!queue.isEmpty()) {
            int len = queue.size();
            while (len-- > 0) {
                String temp = queue.poll();
                // 出口
                if (temp.charAt(Aindex) == 'B' && temp.charAt(Bindex) == 'A') {
                    System.out.println(step);
                    return;
                }
                // 获取空格位置
                int index = temp.indexOf(' ');

                for (int i = 0; i < 4; i++) {
                    int newIndex = index + dir[i];
                    if (newIndex < 0 || newIndex > temp.length() - 1) {
                        continue;
                    }
                    if ((index % 3 == newIndex % 3) || (index / 3 == newIndex / 3)) {
                        //交换
                        char[] tempChar = temp.toCharArray();
                        tempChar[index] = temp.charAt(newIndex);
                        tempChar[newIndex] = temp.charAt(index);
                        String s = new String(tempChar);
                        if (!set.contains(s)) {
                            set.add(s);
                            queue.offer(s);
                        }
                    } 
                }
            }
            step++;
        }
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值