第一次用位运算和十六进制数_poj1753

[size=large][url]http://poj.org/problem?id=1753[/url][/size]
[size=medium][b](1)题意:一个4*4的棋盘,上面放着棋子,棋子要么白色朝上,要么黑色朝上。每一次翻动棋子有两个规则:①只能是16个中的一个。②翻动一个棋子,那么它的上下左右也都要翻动(存在的话)。要求输出使棋盘全为黑或全为白的最少翻动次数。
(2)思想:①搜索方法是用BFS。②翻动棋子采用的是异或运算,所以程序定义了一个int数组。为了表示方便int数组中的数采用十六进制数表示。
(3)Java实现:[/b][/size]


package id0000_1999;

import java.util.ArrayDeque;
import java.util.Scanner;

/**
* 3768K 2985MS ac
*/
public class Id1753 {
//最后两个是棋盘上棋子全黑或着全白的表示。
static int[] op = new int[] { 0x0000c800, 0x0000e400, 0x00007200,
0x00003100, 0x00008c80, 0x00004e40, 0x00002720, 0x00001310,
0x000008c8, 0x000004e4, 0x00000272, 0x00000131, 0x0000008c,
0x0000004e, 0x00000027, 0x00000013, 0x0000ffff, 0x00000000 };

public static void main(String[] args) {

char[] arr;
int chess = 0, count = 0;
Scanner sc = new Scanner(System.in);
while (count < 4) {
arr = sc.nextLine().toCharArray();
for (int i = 0; i < 4; i++) {
chess <<= 1;
if (arr[i] == 'b')
chess++;
}
count++;
}
if (chess == op[16] || chess == op[17]) {
System.out.println(0);
return;
}
arr = null;
sc = null;// 没用的变量名设为null,不知道这样能不能省内存.
count = 0;
Node n;
ArrayDeque<Node> queue = new ArrayDeque<Node>();
while (count < 16) {
int temp = chess ^ op[count];
if (temp == op[16] || temp == op[17]) {
System.out.println(1);
return;
}
n = new Node(count, 1, temp);
//第十六个棋子翻动后诺不能满足要求则不用加到队列中,节约内存。
if (count != 15) {
queue.add(n);
}
count++;
}
while (queue.size() != 0) {
n = queue.pollFirst();
int state = n.state;
int num = n.num + 1;
int step = n.step + 1;
while (num < 16) {
int temp = state ^ op[num];
if (temp == op[16] || temp == op[17]) {
System.out.println(step);
return;
} else {
if (num != 15) {
queue.add(new Node(num, step, temp));
}
}
num++;
}
}
System.out.println("Impossible");
}
}

class Node {

int num;

int step;

int state;

public Node(int num, int step, int state) {

this.num = num;
this.step = step;
this.state = state;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值