题目描述
玛雅人有一种密码,如果字符串中出现连续的2012四个数字就能解开密码。给一个长度为N的字符串,(2=<N<=13)该字符串中只含有0,1,2三种数字,问这个字符串要移位几次才能解开密码,每次只能移动相邻的两个数字。例如02120经过一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此输出为1.如果无论移位多少次都解不开密码,输出-1。
输入描述:
输入包含多组测试数据,每组测试数据由两行组成。
第一行为一个整数N,代表字符串的长度(2<=N<=13)。
第二行为一个仅由0、1、2组成的,长度为N的字符串。
输出描述:
对于每组测试数据,若可以解出密码,输出最少的移位次数;否则输出-1。
示例1
输入
复制
5
02120
输出
复制
1
解题思路,直接暴力穷举,注意此处的暴力范围。
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
while(in.hasNext()){
int N=in.nextInt();
String sc=in.nextLine();
String str=in.nextLine();
if(!f1(str)){
System.out.println(-1); // 判断是否有可能出现2012,如果不可能则直接返回-1
}
else{
Queue queue=new LinkedList<Node>();
Node temp=new Node(0,str);
queue.offer(temp);
Map map=new HashMap<String,Integer>();
while(!queue.isEmpty()){
Node tempnode=(Node)queue.poll();
map.put(tempnode.str,1); //标记该序列
if(tempnode.str.indexOf("2012")>=0){
System.out.println(tempnode.step);
break;
}else{
for(int i=0;i<tempnode.str.length()-1;i++){
char ch[]=tempnode.str.toCharArray();
char tempch=ch[i];
ch[i]=ch[i+1];
ch[i+1]=tempch;
if(!map.containsKey(String.valueOf(ch))){ // 查看该序列是否已经被访问
queue.offer(new Node(tempnode.step+1,String.valueOf(ch))); //将未被访问的序列放入队列
map.put(String.valueOf(ch),1); // 标记该队列
}
}
}
}
}
}
}
//先进行预判断是否有可能出现2012字段
public static boolean f1(String str){
char ch[]=str.toCharArray();
int cnt[]=new int[3];
for(int i=0;i<3;i++){
cnt[i]=0;
}
for(int i=0;i<str.length();i++){
cnt[ch[i]-'0']++;
}
for(int i=0;i<3;i++){
if(cnt[i]==0)
return false;
}
return true;
}
}
class Node{ //该数据结构用于保存形成某一种形式的字符串和其所需要的步数
int step;
String str;
Node(int step,String str){
this.step=step;
this.str=str;
}
}
广度优先搜索+map+队列
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
while(in.hasNext()) {
int len=Integer.valueOf(in.nextLine());
String str=in.nextLine();
if(str.indexOf("2012")>=0)
System.out.println(0);
else {
Map<String,Integer> map=new HashMap<String,Integer>();
map.put(str, 0);
Queue<String> queue=new LinkedList<String>();
queue.offer(str);
boolean flag=false;
while(queue.size()>0) {
if(flag==true)
break;
String str2=new String(queue.poll());
int step=map.get(str2);
char ch[]=str2.toCharArray();
for(int i=0;i<len-1;i++) {
char temp=ch[i];
ch[i]=ch[i+1];
ch[i+1]=temp;
String str3=new String("");
for(int j=0;j<len;j++)
str3+=ch[j];
if(str3.indexOf("2012")>=0){
System.out.println(step+1);
flag=true;
break;
}
else {
if(!map.containsKey(str3)) {
map.put(str3,step+1);
queue.offer(str3);
}
}
temp=ch[i];
ch[i]=ch[i+1];
ch[i+1]=temp;
}
}
if(flag==false)
System.out.println(-1);
}
}
}
}