青蛙跳杯子
题目描述
X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。
X星的青蛙很有些癖好,它们只做3个动作之一:
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要1步,就可跳成下图局面:
WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入为2行,2个串,表示初始局面和目标局面。
输出要求为一个整数,表示至少需要多少步的青蛙跳。
例如:
输入:
*WWBB
WWBB*
则程序应该输出:
2
再例如,
输入:
WWW*BBB
BBB*WWW
则程序应该输出:
10
我们约定,输入的串的长度不超过15
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
不要使用package语句。不要使用jdk1.7及以上版本的特性。
主类的名字必须是:Main,否则按无效代码处理。
----------------------------
笨笨有话说:
我梦见自己是一棵大树,
青蛙跳跃,
我就发出新的枝条,
春风拂动那第 5 层的新枝,
哦,我已是枝繁叶茂。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class mmp {
static String inStr;
static String targetStr;
static List list = new LinkedList<>();
static Map vis = new HashMap<>();
public static void main(String[] args)throws IOException {
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
inStr = bReader.readLine();
targetStr = bReader.readLine();
System.out.println(bfs());
}
public static int bfs (){
Queue queue = new LinkedList<>();
Node node = new Node(String.valueOf(inStr), 0);
queue.add(node);
// list.add(node.str);
vis.put(node.str, true);
while(queue.size() != 0){
node = queue.poll();
if(isOk(node.str)){
return node.step;
}
char[] str = node.str.toCharArray();
int step = node.step;
for(int i=0; i
if(str[i] == '*') continue;
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, j);
node = new Node(String.valueOf(str), step+1);
if (!vis.containsKey(node.str)){
queue.add(node);
// list.add(node.str);
vis.put(node.str, true);
}
str = swap(str, i, j);
}
}
}
return -1;
}
public static char[] swap (char[] str, int i, int j){
char tmp = str[i];
str[i] = str[j+i];
str[j+i] = tmp;
return str;
}
public static boolean isOk(String str){
if (targetStr.equalsIgnoreCase(String.valueOf(str))){
return true;
} else {
return false;
}
}
}
class Node{
int step = 0;
String str;
public Node(String str, int step){
this.str = str;
this.step = step;
}
}
标签:node,Java,String,青蛙,蓝桥,step,static,str
来源: https://blog.csdn.net/a1439775520/article/details/97620201