题目描述
X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一:
- 跳到相邻的空杯子里。
- 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
- 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要1步,就可跳成下图局面:
WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入为2行,2个串,表示初始局面和目标局面。
输出要求为一个整数,表示至少需要多少步的青蛙跳。
样例输入
WWBB
WWBB
样例输出
2
样例输入
WWWBBB
BBBWWW
样例输出
10
数据规模和约定
我们约定,输入的串的长度不超过15
代码
import java.util.*;
public class 青蛙跳杯子 {
public static String s,e;
public static ArrayList<t> map=new ArrayList<t>();
public static HashSet<String> set=new HashSet<String> ();
static class t
{
public String now;
public int sum;
public t(String now,int sum)
{
this.now=now;
this.sum=sum;
}
}
public static void bfs()
{
//System.out.println("-1");
map.add(new t(s,0));
set.add(s);
while(!map.isEmpty())
{
t a=map.get(0);
map.remove(0);
if(a.now.equals(e))
{
System.out.println(a.sum);
return ;
}
else
{
int x=0;
for(int i=0;i<a.now.length();i++)
{
if(a.now.charAt(i)=='*')
{
x=i;
}
}
for(int j=0;j<=6;j++)
{
if(x-3+j>=0&&x-3+j<a.now.length()&&j!=3)
{
char[] strr=a.now.toCharArray();
if(x-3+j>=0&&x-3+j<strr.length&&j!=3)
{
strr=swap(strr,x-3+j,x);
String temp01=String.valueOf(strr);
if(!set.contains(temp01)) { //判定当前行走结果是否已经行走过
set.add(temp01);
map.add(new t(temp01,a.sum+1));
}
strr=swap(strr,x-3+j,x);
}
}
}
}
}
}
public static char[] swap(char[] s,int i,int j)
{
s[i]^=s[j];
s[j]^=s[i];
s[i]^=s[j];
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in =new Scanner ( System.in );
s=in.next();
e=in.next();
bfs();
}
}
我用的是ArrayList但是从网上找的大佬们写的代码都是用Map和LinkedList,于是找了一个模板
package 第三次线下模拟;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
public class 青蛙跳杯子 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String start = sc.next();
String end = sc.next();
sc.close();
Map<String, Boolean> map = new HashMap<String, Boolean>();
Queue<Node> queue = new LinkedList<Node>();
queue.add( new Node(start,0));
map.put(start, true);
while(!queue.isEmpty()){
Node node =queue.poll();
if(node.str.equals(end)){
System.out.println(node.step);
return;
}
int step=node.step;
char[] str = node.str.toCharArray();
for (int i = 0; i < str.length; i++) {
if(str[i]!='*'){
for (int j = -3; j <=3; j++) {
if(i+j<0||i+j>=str.length||j==0||str[i+j]!='*') continue;
str=swap(str,i,i+j);
node = new Node(String.valueOf(str),step+1);
if(!map.containsKey(node.str)){
queue.add(node);
map.put(node.str,true);
}
str=swap(str,i,i+j);
}
}
}
}
}
public static char[] swap(char[] s,int i,int j){
s[i]^=s[j];
s[j]^=s[i];
s[i]^=s[j];
return s;
}
static class Node{
int step = 0;
String str;
public Node(String str, int step){
this.str = str;
this.step = step;
}
}
}