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

**

逻辑无错,多个测试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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值