zoukankan      html  css  js  c++  java
  • 翻转棋问题之“Flip Game”

    题目大意:

      输入4*4的棋盘,用 b 代表 黑色,w 代表 白色。

      输出能把这个棋盘变成同色的最少步数,不可能则输出 Impossible 

      样例: bwwb

          bbwb

          bwwb            -->    4

          bwww

    解题思路:

      枚举每一种可能,使用深搜求解,不要忘了搜索的时候带上步数。

    AC代码:

     1 import java.util.*;
     2 
     3 public class POJ1753{
     4 
     5     static boolean mark[][] = new boolean[8][8];
     6     static int step;
     7     static boolean is_OK;
     8 
     9     static boolean check(){
    10         for(int ii = 1;ii < 5;ii ++){
    11             for(int jj = 1;jj < 5;jj ++){
    12                 if(mark[ii][jj] != mark[1][1]){ return false; }
    13             }
    14         }
    15         return true;
    16     }
    17     
    18     static void flip_them(int x,int y){
    19         mark[x][y] = (!mark[x][y]);
    20         mark[x + 1][y] = (!mark[x + 1][y]);
    21         mark[x - 1][y] = (!mark[x - 1][y]);
    22         mark[x][y + 1] = (!mark[x][y + 1]);
    23         mark[x][y - 1] = (!mark[x][y - 1]);
    24     }
    25 
    26     static void dfs(int x,int y,int steps){
    27         if(steps >= step){
    28             is_OK = check();
    29             return ;
    30         }
    31         if(is_OK == true || x >= 5){return ;}
    32         flip_them(x,y);
    33         if(y < 4){dfs(x,y + 1,steps + 1);}
    34         else {dfs(x + 1,1,steps + 1);}
    35         flip_them(x,y);
    36         if(y < 4){dfs(x,y + 1,steps);}
    37         else {dfs(x + 1,1,steps);}    
    38     }
    39 
    40     public static void main(String[] args){
    41         Scanner sc = new Scanner(System.in);
    42         while(sc.hasNext()){
    43             is_OK = false;
    44             for(int ii = 0;ii < 7;ii ++){
    45                 for(int jj = 0;jj < 7;jj ++){ mark[ii][jj] = true; }
    46             }
    47             for(int i = 1;i <= 4;i ++){
    48                 String t = sc.nextLine();
    49                 for(int j = 1;j <= 4;j ++){
    50                     if(t.charAt(j - 1) == 'b'){ mark[i][j] = true; }
    51                     else{ mark[i][j] = false; }
    52                 }
    53             }
    54             for(step = 0;step <= 16;step ++){
    55                 dfs(1,1,0);
    56                 if(is_OK == true){break;}
    57             }
    58             if(is_OK == true){System.out.println(step);}
    59             else if(is_OK == false){System.out.println("Impossible");}
    60         }
    61     }
    62 }
  • 相关阅读:
    七层网络模型
    nginx配置本地https
    kong结合consul
    kong添加upstream
    1.创建spring cloud父工程和子模块
    idea自动生成spring实体
    php的json_encode()之后float类型丢失精度
    windows下wnmp配置
    Call to undefined function imageftbbox()
    介绍一款比较好用的画图工具--PlantUml
  • 原文地址:https://www.cnblogs.com/love-fromAtoZ/p/7551352.html
Copyright © 2011-2022 走看看