魔板 BFS 最短路径 字符串处理 操作模拟 java

🍑 算法题解专栏


🍑 魔板

在这里插入图片描述
输入

2 6 8 4 5 7 3 1

输出

7
BCABCCB

🍑 操作函数(一维数组表示魔板状态)

在这里插入图片描述

🍑 字符串比较:String.equals(String a)

import java.util.*;

public class Main
{
	static String end;

	static class Pair
	{
		char[] now;
		String path;

		public Pair(char[] now, String path)
		{
			super();
			this.now = now;
			this.path = path;
		}
	}

	static void bfs()
	{
		String start = "12345678";
		if (start.equals(end))
		{
			System.out.println(0);
			return;
		}

		char[] sta = start.toCharArray();
		HashSet<String> set = new HashSet<>();
		LinkedList<Pair> q = new LinkedList<>();
		set.add(start);
		q.add(new Pair(sta, ""));
		while (!q.isEmpty())
		{
			Pair t = q.poll();
			char[] cc = t.now;
			String path = t.path;
//			System.out.println(String.valueOf(cc) + " " + path);
//			if (q.size() == 1)
//				System.out.println("debug");
			for (char i = 'A'; i <= 'C'; i++)
			{
				String ss = op(i, cc);
				if (set.contains(ss))
					continue;
				set.add(ss);
				String newPath = path + i;
//				System.out.println(String.valueOf(cc) + " " + i + " " + ss);
//				System.out.println(newPath);
				q.add(new Pair(ss.toCharArray(), newPath));
				if (ss.equals(end))
				{
					int len = newPath.length();
					System.out.println(len);
					if (len > 0)
						System.out.println(newPath);
					return;
				}
			}
		}
	}

	static String op(char type, char[] cc)
	{
		char[] ans = new char[8];
		if (type == 'A')
		{
			ans[0] = cc[7];
			ans[1] = cc[6];
			ans[2] = cc[5];
			ans[3] = cc[4];
			ans[4] = cc[3];
			ans[5] = cc[2];
			ans[6] = cc[1];
			ans[7] = cc[0];
		} else if (type == 'B')
		{
			ans[0] = cc[3];
			ans[1] = cc[0];
			ans[2] = cc[1];
			ans[3] = cc[2];
			ans[4] = cc[5];
			ans[5] = cc[6];
			ans[6] = cc[7];
			ans[7] = cc[4];
		} else if (type == 'C')
		{
			ans[0] = cc[0];
			ans[1] = cc[6];
			ans[2] = cc[1];
			ans[3] = cc[3];
			ans[4] = cc[4];
			ans[5] = cc[2];
			ans[6] = cc[5];
			ans[7] = cc[7];
		}
//		System.out.println(String.valueOf(ans));
		return String.valueOf(ans);
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		end = line.replaceAll(" ", "");
//		System.out.println(end);

		bfs();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值