加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
lights_out.cpp 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
bostonhsu 提交于 2023-11-09 20:55 . algorithm of lights out 3x3.
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
using namespace std;
#define ROWS 3
#define COLS 3
char oriLights[ROWS];
char lights[ROWS];
char result[ROWS];
int GetBit(char 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, char result[])
{
cout << "PUZZLE #" << t << endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
cout << GetBit(result[i], 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 nmax = 1 << COLS;
for (int n = 0; n < nmax; ++n) {
memcpy(lights, oriLights, sizeof(oriLights));
switchs = n;
for (int i = 0; i < ROWS; ++i) {
result[i] = switchs;
for (int j = 0; j < COLS; ++j) {
if (GetBit(switchs, j)) { // the 1 in a row bingo, then flip it and all adjesants.
if (j > 0) { // if middles
FlipBit(lights[i], j-1); // flip its left.
}
FlipBit(lights[i], j); // flip itself.
if (j < COLS-1) { // if middles
FlipBit(lights[i], j+1); // flip its right.
}
}
}
if (i < ROWS-1) {
lights[i+1] ^= switchs;
}
switchs = lights[i];
}
if (lights[ROWS-1] == 0) {
OutputResult(t, result);
break;
}
}
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化