hihocoder 1654
http://hihocoder.com/problemset/problem/1654?sid=1249752
思路:广搜
1 import java.util.Arrays; 2 import java.util.HashMap; 3 import java.util.LinkedList; 4 import java.util.Map; 5 import java.util.Queue; 6 import java.util.Scanner; 7 8 public class Main { 9 public static void main(String[] args) { 10 Scanner cin = new Scanner(System.in); 11 String str[] = new String[10]; 12 for(int i = 0;i<4;i++) 13 str[i] = cin.next(); 14 Map<String, Integer>s = new HashMap<>(); 15 String tmp =str[0]+str[1]+str[2]+str[3]; 16 char [][]str1 = new char[10][10]; 17 if(check(tmp)==1) 18 System.out.println(0); 19 else { 20 s.clear(); 21 s.put(tmp, 0); 22 int [][]dir = {{1,0},{0,1},{-1,0},{0,-1}}; 23 Queue<String>q = new LinkedList<>(); 24 q.add(tmp); 25 boolean flag = false; 26 while(!q.isEmpty()){ 27 tmp = q.poll(); 28 //System.out.println(tmp.substring(0, 4)+"\n"+tmp.substring(4, 8)+"\n"+tmp.substring(8, 12)+"\n"+tmp.substring(12, 16)+" "+"num:"+s.get(tmp)); 29 if(check(tmp)>=1){ 30 System.out.println(s.get(tmp)); 31 flag = true; 32 break; 33 } 34 str1[0] = tmp.substring(0, 4).toCharArray(); 35 str1[1] = tmp.substring(4,8).toCharArray(); 36 str1[2] = tmp.substring(8, 12).toCharArray(); 37 str1[3] = tmp.substring(12, 16).toCharArray(); 38 for(int i = 0;i<4;i++) 39 for(int j = 0;j<4;j++){ 40 if(str1[i][j]!='O'){ 41 for(int k = 0;k<4;k++){ 42 int x = i+dir[k][0]; 43 int y = j+dir[k][1]; 44 if(x>=0&&x<4&&y>=0&&y<4&&str1[x][y]=='O'){ 45 str1[x][y] = str1[i][j]; 46 str1[i][j] = 'O'; 47 String tmp1=""; 48 for(int i1 = 0;i1<4;i1++) 49 for(int j1=0;j1<4;j1++) 50 tmp1+=str1[i1][j1]; 51 //System.out.println("tmp1:"+tmp1); 52 if(!s.containsKey(tmp1)){ 53 s.put(tmp1, s.get(tmp)+1); 54 q.add(tmp1); 55 } 56 str1[i][j] = str1[x][y]; 57 str1[x][y] ='O'; 58 } 59 } 60 } 61 } 62 } 63 if(!flag) 64 System.out.println(-1); 65 } 66 } 67 68 public static int check(String x){ 69 for(int i = 0;i<16;i+=4){ 70 if(x.charAt(0+i)==x.charAt(1+i)&&x.charAt(1+i)==x.charAt(2+i)&&x.charAt(2+i)==x.charAt(3+i)&&x.charAt(0+i)!='O') 71 return 1; 72 } 73 for(int i = 0;i<4;i++) 74 if(x.charAt(i)==x.charAt(i+4)&&x.charAt(i)==x.charAt(i+8)&&x.charAt(i)==x.charAt(i+12)&&x.charAt(i)!='O') 75 return 2; 76 if(x.charAt(0)==x.charAt(5)&&x.charAt(0)==x.charAt(10)&&x.charAt(0)==x.charAt(15)&&x.charAt(0)!='O') 77 return 3; 78 79 if(x.charAt(3)==x.charAt(6)&&x.charAt(3)==x.charAt(9)&&x.charAt(3)==x.charAt(12)&&x.charAt(3)!='O') 80 return 4; 81 return 0; 82 } 83 }