(BFS,状态存储的优化)Flip Game

本文介绍了一种使用广度优先搜索(BFS)算法解决FlipGame问题的方法,目标是在最少的步骤内使所有棋子颜色统一。文章提供了两种实现思路:一种是通过整数操作简化搜索过程;另一种则是直接操作棋盘状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flip Game

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 7   Accepted Submission(s) : 4
Problem Description
Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules: 
  1. Choose any one of the 16 pieces. 
  2. Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).

Consider the following position as an example: 

bwbw 
wwww 
bbwb 
bwwb 
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become: 

bwbw 
bwww 
wwwb 
wwwb 
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal. 
 

Input
The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.
 

Output
Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes).
 

Sample Input
bwwb bbwb bwwb bwww
 

Sample Output
4
 

Source
PKU
 
题目大意:给定一棋局状态,通过规定操作(翻转某一棋子以及它四个方向的棋子)是全部棋子为白棋或黑棋,要求最小步数.
分析:简单BFS.注意状态存储是将棋局编码成一个整数(有效位为16位).
此题其实可以剪枝(每次访问一个棋局都将它对应所有的等效棋局标记,即旋转旋转旋转,延任一对角线或边平分线翻转,再旋转旋转旋转),但由于数据弱,或数据只有一组,或游戏性质的原因,此题没有剪枝也AC了.
另外,由于可以将棋局编码成一个整数,搜索时对棋局的操作也可以用对整数的操作代替.

用操作整数代替操作棋局:
#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 1<<16
struct NODE
{
	int m;
	int step;
}Q[maxn], u, t;
bool mark[maxn];
char m[4][5];
int flag;
int head, tail;
int connect[16][5] = { { 16, 15, 12, 0, 0 }, { 15, 16, 14, 11, 0 }, { 14, 15, 13, 10, 0 }, { 13, 14, 9, 0, 0 }, { 12, 16, 11, 8, 0 }, { 11, 15, 12, 10, 7 }, { 10, 14, 11, 9, 6 }, { 9, 13, 10, 5, 0 }, { 8, 12, 7, 4, 0 }, { 7, 11, 8, 6, 3 }, { 6, 10, 7, 5, 2 }, { 5, 9, 6, 1, 0 }, { 4, 8, 3, 0, 0 }, { 3, 7, 4, 2, 0 }, { 2, 6, 3, 1, 0 }, { 1, 5, 2, 0, 0 } };
int Exchange()
{
	int z = 0;
	for (int i = 0; i < 4; i++)
	for (int j = 0; j < 4; j++)
	{
		z = z << 1;
		if (m[i][j] == 'b')
			z += 1;
	}
	return z;
}
int flip(int z, int j)
{
	return z ^ (1 << (j - 1));
}
int Flip(struct NODE &u, int i)
{
	int z = u.m;
	for (int j = 0; j < 5; j++)
	{
		if (connect[i][j])
			z = flip(z, connect[i][j]);
	}
	return z;
}
void BFS()
{
	head = tail = 0;

	t.m = Exchange();	t.step = 0;
	Q[tail++] = t;
	if (t.m == (1 << 16) - 1 || t.m == 0)
	{
		flag = 1;
		return;
	}
	mark[t.m] = true;
	while (head < tail)
	{
		u = Q[head++];
		for (int i = 0; i < 16; i++)
		{
			t.m = Flip(u, i);	t.step = u.step + 1;
			if (mark[t.m] == false)
			{
				Q[tail++] = t;
				if (t.m == (1 << 16) - 1 || t.m == 0)
				{
					flag = 1;
					return;
				}
				mark[t.m] = true;
			}
		}
	}
}
int main()
{
	//freopen("f:\\input.txt", "r", stdin);
	int i;
	for (i = 0; i < 4; i++)
		scanf("%s", m[i]);

	memset(mark, false, sizeof(mark));
	flag = 0;
	BFS();

	if (flag)
		printf("%d\n", Q[tail - 1].step);
	else
		printf("Impossible\n");

	return 0;
}

常规方法:
#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 1<<16
struct NODE
{
	char m[4][4];
	int step;
}Q[maxn], u, t;
bool mark[maxn];
int dx[5] = { 0, 0, -1, 0, 1 }, dy[5] = { 0, -1, 0, 1, 0 };
int flag;
int head, tail;
int z;
int Exchange(struct NODE &a)
{
	int z = 0;
	for (int i = 0; i < 4; i++)
	for (int j = 0; j < 4; j++)
	{
		z = z << 1;
		if (a.m[i][j] == 'b')
			z += 1;
	}
	return z;
}
void Visit(struct NODE &a)
{
	int jud = Exchange(a);
	Q[tail++] = a;
	if (jud == (1 << 16) - 1 || jud == 0)
	{
		flag = 1;
		return;
	}
	mark[jud] = true;
}

void Update(struct NODE &u,struct NODE &a, int i, int j)
{
	a = u;
	for (int k = 0; k < 5; k++)
	{
		int x = i + dx[k];
		int y = j + dy[k];
		if (0 <= x&&x < 4 && 0 <= y&&y < 4)
			a.m[x][y] = (u.m[x][y] == 'b' ? 'w' : 'b');
	}
	a.step = u.step + 1;
}
void BFS()
{
	head = tail = 0;
	t.step = 0;

	Q[tail++] = t;
	int jud = Exchange(t);
	if (jud == (1 << 16) - 1 || jud == 0)
	{
		flag = 1;
		return;
	}
	mark[jud] = true;
	while (head < tail)
	{
		u = Q[head++];
		for (int i = 0; i < 4; i++)
		for (int j = 0; j < 4;j++)
		{
			Update(u,t, i,j);
			int jud = Exchange(t);
			if (mark[jud] == false)
			{
				Q[tail++] = t;
				if (jud == (1 << 16) - 1 || jud == 0)
				{
					flag = 1;
					return;
				}
				mark[jud] = true;
			}
		}
	}
}
int main()
{
	freopen("f:\\input.txt", "r", stdin);
	int i, j;
	for (i = 0; i < 4; i++)
		scanf("%s", &t.m[i]);
	memset(mark, false, sizeof(mark));
	flag = 0;
	BFS();

	if (flag)
		printf("%d\n", Q[tail - 1].step);
	else
		printf("Impossible\n");
	return 0;
}




import numpy as np import random import time from collections import deque import os # 迷宫生成类 class MazeGenerator: @staticmethod def generate_maze(width, height): """使用DFS算法生成迷宫""" # 初始化迷宫(1表示墙,0表示路径) maze = np.ones((height, width), dtype=int) # 起点和终点 start = (1, 1) end = (height - 2, width - 2) # DFS生成迷宫 stack = [start] maze[start] = 0 while stack: current = stack[-1] x, y = current # 获取未访问的邻居(距离为2的单元格) neighbors = [] for dx, dy in [(0, 2), (2, 0), (0, -2), (-2, 0)]: nx, ny = x + dx, y + dy if 0 < nx < height - 1 and 0 < ny < width - 1 and maze[nx, ny] == 1: # 修正:将墙位置单独存储 wall_pos = (x + dx//2, y + dy//2) neighbors.append((nx, ny, wall_pos)) # 现在是三元组 if neighbors: # 修正:正确解包三元组 next_x, next_y, wall_pos = random.choice(neighbors) next_cell = (next_x, next_y) maze[next_cell] = 0 maze[wall_pos] = 0 stack.append(next_cell) else: stack.pop() # 设置起点和终点 maze[start] = 2 # 起点标记为2 maze[end] = 3 # 终点标记为3 return maze # 迷宫游戏类 class MazeGame: def __init__(self): self.maze = None self.rat_pos = None self.steps = 0 self.start_time = 0 self.visited = set() def load_maze(self, level): """根据难度级别加载迷宫""" filename = f'level{level}.txt' if not os.path.exists(filename): # 如果迷宫文件不存在,则生成 if level == 1: size = 12 elif level == 2: size = 20 else: size = 40 maze = MazeGenerator.generate_maze(size, size) np.savetxt(filename, maze, fmt='%d') else: maze = np.loadtxt(filename, dtype=int) self.maze = maze self.rat_pos = tuple(np.argwhere(maze == 2)[0]) # 初始位置 self.steps = 0 self.start_time = time.time() self.visited = set([self.rat_pos]) return maze def print_maze(self): """打印迷宫和老鼠当前位置""" os.system('cls' if os.name == 'nt' else 'clear') # 清屏 print(f"步数: {self.steps} | 用时: {time.time() - self.start_time:.1f}秒") for i, row in enumerate(self.maze): line = '' for j, cell in enumerate(row): if (i, j) == self.rat_pos: line += '🐭' # 老鼠位置 elif (i, j) in self.visited: line += '· ' # 已访问路径 elif cell == 0: line += ' ' # 路径 elif cell == 1: line += '██' # 墙 elif cell == 2: line += '🚪' # 起点 elif cell == 3: line += '🏁' # 终点 print(line) def move_rat(self, direction): """根据方向移动老鼠""" dx, dy = 0, 0 if direction == 'up': dx = -1 elif direction == 'down': dx = 1 elif direction == 'left': dy = -1 elif direction == 'right': dy = 1 new_pos = (self.rat_pos[0] + dx, self.rat_pos[1] + dy) # 检查移动是否有效 if (0 <= new_pos[0] < self.maze.shape[0] and 0 <= new_pos[1] < self.maze.shape[1] and self.maze[new_pos] != 1): # 不是墙 self.rat_pos = new_pos self.steps += 1 self.visited.add(new_pos) return True return False def is_completed(self): """检查是否到达终点""" return self.maze[self.rat_pos] == 3 def bfs_solve(self): """使用BFS算法自动求解迷宫""" start = tuple(np.argwhere(self.maze == 2)[0]) end = tuple(np.argwhere(self.maze == 3)[0]) # BFS寻路 queue = deque([start]) visited = {start: None} # 记录路径 while queue: current = queue.popleft() if current == end: break # 探索四个方向 for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: next_pos = (current[0] + dx, current[1] + dy) if (0 <= next_pos[0] < self.maze.shape[0] and 0 <= next_pos[1] < self.maze.shape[1] and self.maze[next_pos] != 1 and next_pos not in visited): queue.append(next_pos) visited[next_pos] = current # 回溯路径 if end not in visited: return [] # 没有找到路径 path = [] current = end while current != start: path.append(current) current = visited[current] path.reverse() return path # 键盘交互模式 def keyboard_mode(level): game = MazeGame() game.load_maze(level) print("使用方向键移动老鼠,🐭代表老鼠,🚪起点,🏁终点") print("按ESC键退出游戏") game.print_maze() try: while True: key = input("方向键 (w=上, s=下, a=左, d=右): ").lower() if key == 'esc': break direction = None if key == 'w': direction = 'up' elif key == 's': direction = 'down' elif key == 'a': direction = 'left' elif key == 'd': direction = 'right' if direction and game.move_rat(direction): game.print_maze() # 检查是否到达终点 if game.is_completed(): print(f"恭喜!老鼠成功走出迷宫!步数: {game.steps}, 用时: {time.time() - game.start_time:.1f}秒") break except KeyboardInterrupt: print("\n游戏已退出") # 自动求解模式 def auto_solve(level): game = MazeGame() game.load_maze(level) print("正在自动求解迷宫...") path = game.bfs_solve() if not path: print("没有找到解决方案!") return # 显示初始状态 game.print_maze() time.sleep(1) # 逐步显示路径 for i, pos in enumerate(path): game.rat_pos = pos game.steps = i + 1 game.print_maze() time.sleep(0.1) print(f"自动求解完成!步数: {len(path)}, 用时: {time.time() - game.start_time:.1f}秒") # 主程序 def main(): print("=== 电子老鼠走迷宫游戏 ===") print("难度级别:") print("1. 简单 (12x12)") print("2. 中等 (20x20)") print("3. 困难 (40x40)") while True: try: level = int(input("请选择难度级别 (1-3): ")) if level in [1, 2, 3]: break else: print("无效的难度选择,请重新输入!") except ValueError: print("请输入一个有效的数字 (1-3)!") print("\n游戏模式:") print("1. 键盘交互") print("2. 自动求解") while True: try: mode = int(input("请选择模式 (1-2): ")) if mode in [1, 2]: break else: print("无效的模式选择,请重新输入!") except ValueError: print("请输入一个有效的数字 (1-2)!") if mode == 1: keyboard_mode(level) elif mode == 2: auto_solve(level) if __name__ == "__main__": main() 帮我完善一下这个代码
最新发布
06-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值