题目
X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一:
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
思路
只要下标不越界而且没有被搜过,就可以进入队列进行广搜
用广搜咯,再来个Hashset作为标记,标记到底这种情况以前有没有搜过,这样子就可以了【这个地方一定要记得没有搜过的在搜索后一定要加入到set里面,不然就超时】
代码
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Point{
int step;//步数
String now;//当前状态
int index_blank;//空杯子的位置
}
public class Main {
static String start;//初始状态
static String end;//最终状态
static HashSet<String> set=new HashSet();//标记集合
static Queue<Point> queue=new LinkedList();//队列
//左右指针界限
static int right;
//往左边和右边跳的情形
static int direction[]={-1,-2,-3,1,2,3};
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
start=reader.nextLine();//初始状态
end= reader.nextLine();//最终状态
right=start.length()-1;
set.clear();
queue.clear();
Point temp=new Point();
temp.now=start;
temp.step=0;
for (int i=0;i<=right;++i)
if (start.charAt(i)=='*')
{
temp.index_blank=i;
break;
}
queue.offer(temp);
set.add(start);//已经走过当前状态
while(!queue.isEmpty())
{
String now=queue.peek().now;//当前字符串
int step=queue.peek().step;//步数
int index=queue.peek().index_blank;
if (now.equals(end))
{
System.out.println(step);
return;
}
//广搜六种状态
for (int i=0;i<=5;++i)
{
int temporary_index=index+direction[i];//步数的六个方向
if (check(temporary_index))//坐标是否在范围内
{
String temporary_now=change(temporary_index,index,now);
if (!set.contains(temporary_now))//没有搜索到
{
Point g=new Point();
g.now=temporary_now;
g.step=step+1;
g.index_blank=temporary_index;
set.add(temporary_now);
queue.offer(g);
}
}
}
queue.poll();
}
}
//检查坐标是否合格
public static boolean check(int n){
return n>=0 && n<=right;
}
//传入新下标,老下标和老得字符串,返回最终的新字符串
public static String change(int a,int b,String old) {
StringBuffer result = new StringBuffer(old);
result.replace(a, a+1, "*");
result.replace(b, b+1, "" + old.charAt(a));
return result.toString();
}
}
结果
虽然ac了,可是由于忘记在搜索过后把被搜索的加入到set里面,结果wa了好几次。以后这种小细节要切记!
切记不要遗漏掉标记!