加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
lights_out_brute.cpp 4.19 KB
一键复制 编辑 原始数据 按行查看 历史
bostonhsu 提交于 2023-11-10 02:13 . algorithm of lights out brute of 5x6.
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
using namespace std;
#define ROWS 5
#define COLS 6
char oriLights[ROWS];
char lights[ROWS];
char result[ROWS];
int GetBit(int c, int i)
{
return (c >> i) & 1;
}
void SetBit(char & c, int i, int v)
{
if (v) {
c |= (1 << i);
}
else {
c &= ~(1 << i);
}
}
void FlipBit(char & c, int i)
{
c ^= (1 << i);
}
void OutputResult(int t, int result)
{
cout << "PUZZLE #" << t << endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
cout << GetBit(result, i*COLS+j);
if (j < COLS) {
cout << " ";
}
}
cout << endl;
}
}
int main()
{
char switchs;
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
memset(oriLights, 0, sizeof(oriLights));
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int s;
cin >> s;
SetBit(oriLights[i], j, s);
}
}
int tryMax = 1 << (COLS*ROWS);
for (int tryNum = 0; tryNum < tryMax; ++tryNum) {
memcpy(lights, oriLights, sizeof(oriLights)); // lights would be changed in each loop.
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (GetBit(tryNum, row*COLS+col)) {
FlipBit(lights[row], col); // flip center
if (row == 0) {
if (col == 0)
{
FlipBit(lights[row], col+1);
FlipBit(lights[row+1], col);
} else if (col == COLS-1)
{
FlipBit(lights[row], col-1);
FlipBit(lights[row+1], col);
} else {
FlipBit(lights[row], col-1);
FlipBit(lights[row], col+1);
FlipBit(lights[row+1], col);
}
} else if (row == ROWS-1)
{
if (col == 0)
{
FlipBit(lights[row], col+1);
FlipBit(lights[row-1], col);
} else if (col == COLS-1)
{
FlipBit(lights[row], col-1);
FlipBit(lights[row-1], col);
} else
{
FlipBit(lights[row], col-1);
FlipBit(lights[row], col+1);
FlipBit(lights[row-1], col);
}
} else {
if (row == 0)
{
FlipBit(lights[row-1], col);
FlipBit(lights[row+1], col);
FlipBit(lights[row], col+1);
} else if (col == COLS-1)
{
FlipBit(lights[row-1], col);
FlipBit(lights[row+1], col);
FlipBit(lights[row], col-1);
} else {
FlipBit(lights[row-1], col);
FlipBit(lights[row+1], col);
FlipBit(lights[row], col-1);
FlipBit(lights[row], col+1);
}
}
}
}
}
bool isOK = true;
for (int i = 0; i < ROWS; i++)
{
if (lights[i] != 0)
{
isOK = false;
break;
}
}
if (isOK)
{
OutputResult(t, tryNum);
break;
}
}
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化