FlipGame循环解法(此方法未能体现bfs精髓,有冗余之处)

来源:互联网 发布:lb网络用语 编辑:程序博客网 时间:2024/06/05 09:56

**

逻辑无错,多个测试case无错,但WA,不知为何。

**
import java.util.Scanner;

public class FlipGame3 {
static boolean[][] chess = new boolean[6][6];
static int[][] queue;
static int head;
static int tail;
static boolean flag = false;
static int step;
static int[] Dx = new int[] { -1, 1, 0, 0, 0 };
static int[] Dy = new int[] { 0, 0, -1, 1, 0 };

public static void main(String[] args) throws FileNotFoundException {    // TODO Auto-generated method stub    Scanner sc = new Scanner(System.in);    String[] tmpread;    for (int i = 1; i < 5; i++) {        tmpread = sc.nextLine().split("");        for (int j = 1; j < 5; j++) {            if (tmpread[j - 1].equals("b"))                chess[i][j] = true;        }    }    if (judge_all()) {        flag = true;        step = 0;    } else {        for (step = 1; step <= 16; step++) {            queue = new int[step+1][2];            head = 0;            tail = 0;            queue[tail++]=new int[]{1,1};            FlipPath();            if (flag)                break;        }    }    if (flag)        System.out.println(step);    else        System.out.println("Impossible");}private static void FlipPath() {    // TODO Auto-generated method stub    int x=1,y=1;    while (true) {        while (true) {            if (head == step) {                flag = judge_all();                break;            }            x=queue[head][0];            y=queue[head][1];            if (x == 5)                break;            flip(x, y);            if (y < 4)                queue[tail++]=new int[]{x,y+1};            else                queue[tail++]=new int[]{x+1,1};            head++;        }        head--;        tail--;        if(flag||head==-1)            break;        x=queue[head][0];        y=queue[head][1];        flip(x, y);        if (y < 4)            queue[head]=new int[]{x,y+1};        else            queue[head]=new int[]{x+1,1};    }}private static void flip(int x, int y) {    // TODO Auto-generated method stub    for (int i = 0; i < 5; i++)        chess[x + Dx[i]][y + Dy[i]] = !chess[x + Dx[i]][y + Dy[i]];}private static boolean judge_all() {    // TODO Auto-generated method stub    for (int i = 1; i < 5; i++) {        for (int j = 1; j < 5; j++) {            if (chess[i][j] != chess[1][1])                return false;        }    }    return true;}

}

sample input:
bwwb
bbwb
bwwb
bwww

sample output:
4

0 0
原创粉丝点击