Maze CodeForces - 377A(DFS)

Pavel 喜欢网格迷宫。一个网格迷宫是一个 n × m 的长方形迷宫,其中每个单元格要么是空白的,要么是墙体。您可以从一个单元格走到另一个单元格,只要两个单元格均是空白的,且拥有一条公共的边。

Pavel 绘制了一个网格迷宫,包含的全部空白单元格形成了一个连通区域。换言之,您可以从任何一个空白的单元格,走到其它任意的空白单元格。Pavel 的迷宫如果墙体太少,他就不喜欢这个迷宫。他希望将 k 个空白的单元格转换为墙体,使得剩余的全部单元格仍然能够形成一个连通区域。请帮助他实现这个任务。

输入

第一行包含了三个整数 n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s),其中 nm 分别是迷宫的高度和宽度,k 是 Pavel 希望加入的墙体数目,并且字母 s 表示原始迷宫中的空白单元格数目。

接下来的 n 行中,每行包含 m 个字符。它们描述了原始的迷宫。如果某行中的一个字符等于 ".",则相应的单元格为空白;如果字符等于 "#",则单元格为墙体。

输出

打印 n 行,每行包含 m 个字符:符合 Pavel 需求的新迷宫。将已转换为墙体的原始空白单元格标识为 "X";其它单元格必须保留为未更改状态 (也就是 "." 和 "#")。

数据保证:存在一个解决方案。如果有多个解决方案,可输出它们中的任意一个。

示例

输入

3 4 2
#..#
..#.
#...

输出

#.X#
X.#.
#...

输入

5 4 5
#...
#.#.
.#..
...#
.#.#

输出

#XXX
#X#.
X#..
...#
.#.#

就是一个构造地图的DFS 题目,一开始就瞎写一通,逻辑也不是很对,最终也没有写出来,后来看了大神的代码,还是比较巧妙的,我们可以转化一下问题,正面想就是找出 一些点,使剩下的点可以走通(求一个联通分量,判断剩下的点是不是联通的 ),但是这样想就很难实现了,很麻烦,没有做出来。大神的代码是先走n-k(地图上点一共 n个,要放置k个墙)个点,将这个走过的路径都当做剩下联通点(肯定是联通的,因为是一步一步走过来的),剩下没有走过的点就是放置墙的点,巧妙的解法。这个题目还是有几点是值得学习的,我们在记录已经走过了几个点的时候,我们这时候有两个选择,来一个DFS形参或者一个全局变量,这里需要格外注意,如果我们选择形参的话,我们会出现错误,因为形参在DFS递归的时候会根据你当前的状态变化的,而全局变量是不会变的,所以我们在做DFS的时候,我们需要认清楚我们需要什么的参数。*****很重要的

#include<iostream>
using namespace std;
const int maxn=505;


int a[]={0,0,1,-1};
int b[]={1,-1,0,0};

char maap[maxn][maxn];
int vis[maxn][maxn];
bool flag2=false;
int n,m,k,num;

int kase;
void dfs(int x,int y)
{
	kase++;
	if(flag2)
		return ;
	
	if(kase>=num-k)
	{
		flag2=true;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(vis[i][j])
					cout<<maap[i][j];
				else if(maap[i][j]!='#')
					cout<<'X';
				else
					cout<<'#';	
			}
			cout<<endl;
			
		}
		
		return ;
	}
	for(int i=0;i<4;i++)
	{
		int xx=x+a[i];
		int yy=y+b[i];
		if(maap[xx][yy]=='.'&&xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]!=1)
		{
			vis[xx][yy]=1;
			dfs(xx,yy);
		}
		
	}
}

int main()
{
	cin>>n>>m>>k;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			cin>>maap[i][j];
			if(maap[i][j]=='.')
				num++; 
		}
	}
	
	bool flag=false;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(maap[i][j]=='.')
			{
				vis[i][j]=1;
				dfs(i,j);
				break;
			}
		}
		
		
	}
	return 0;
}

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是 `freegames.maze` 模块的详细注释: ```python """ freegames.maze This module provides functions to create and manipulate mazes. Functions: maze(width, height, complexity=0.75, density=0.75): Create a maze with the given dimensions and complexity/density. Classes: Maze: A maze object that can be displayed and solved using Turtle graphics. """ import random def maze(width, height, complexity=0.75, density=0.75): """ Create a maze with the given dimensions and complexity/density. Parameters: - width (int): the width of the maze in cells. - height (int): the height of the maze in cells. - complexity (float): a value between 0 and 1 that determines the amount of complexity/number of twists and turns in the maze. - density (float): a value between 0 and 1 that determines the amount of density/number of cells that are filled in the maze. Returns: - A 2D list of booleans representing the maze, where True indicates a wall and False indicates a path. """ # Determine the dimensions of the maze in cells. rows = height // 2 + 1 cols = width // 2 + 1 # Create the maze as a 2D list of booleans. maze = [[False] * cols for i in range(rows)] # Fill in the border cells as walls. for i in range(rows): maze[i][0] = maze[i][-1] = True for j in range(cols): maze[0][j] = maze[-1][j] = True # Fill in the maze with walls and paths. for i in range(1, rows - 1): for j in range(1, cols - 1): if random.random() < density: maze[i][j] = True elif i % 2 == 0 or j % 2 == 0: maze[i][j] = True # Carve out the maze starting from the center. start_x, start_y = rows // 2, cols // 2 maze[start_x][start_y] = False cells = [(start_x, start_y)] while cells: current = cells.pop(random.randint(0, len(cells) - 1)) x, y = current neighbors = [] if x > 1 and not maze[x - 2][y]: neighbors.append((x - 2, y)) if x < rows - 2 and not maze[x + 2][y]: neighbors.append((x + 2, y)) if y > 1 and not maze[x][y - 2]: neighbors.append((x, y - 2)) if y < cols - 2 and not maze[x][y + 2]: neighbors.append((x, y + 2)) if neighbors: cells.append(current) neighbor = neighbors[random.randint(0, len(neighbors) - 1)] nx, ny = neighbor if nx == x - 2: maze[x - 1][y] = False elif nx == x + 2: maze[x + 1][y] = False elif ny == y - 2: maze[x][y - 1] = False elif ny == y + 2: maze[x][y + 1] = False maze[nx][ny] = False return maze class Maze: """ A maze object that can be displayed and solved using Turtle graphics. Attributes: - maze (list): a 2D list of booleans representing the maze. - width (int): the width of the maze in cells. - height (int): the height of the maze in cells. - cell_size (int): the size of each cell in pixels. - turtle (turtle.Turtle): the turtle used to draw the maze. - screen (turtle.Screen): the screen used to display the maze. Methods: - __init__(self, maze, cell_size=10): create a new Maze object. - _draw_wall(self, row, col): draw a wall at the given cell. - _draw_path(self, row, col): draw a path at the given cell. - display(self): display the maze using Turtle graphics. - solve(self, start=(0, 0), end=None): solve the maze using the given start and end positions, and return a list of (row, col) tuples representing the solution path. """ def __init__(self, maze, cell_size=10): """ Create a new Maze object. Parameters: - maze (list): a 2D list of booleans representing the maze. - cell_size (int): the size of each cell in pixels. """ self.maze = maze self.width = len(maze[0]) self.height = len(maze) self.cell_size = cell_size self.turtle = None self.screen = None def _draw_wall(self, row, col): """ Draw a wall at the given cell. Parameters: - row (int): the row number of the cell. - col (int): the column number of the cell. """ x = col * self.cell_size y = row * self.cell_size self.turtle.goto(x, y) self.turtle.setheading(0) self.turtle.pendown() for i in range(4): self.turtle.forward(self.cell_size) self.turtle.left(90) self.turtle.penup() def _draw_path(self, row, col): """ Draw a path at the given cell. Parameters: - row (int): the row number of the cell. - col (int): the column number of the cell. """ x = col * self.cell_size + self.cell_size // 2 y = row * self.cell_size + self.cell_size // 2 self.turtle.goto(x, y) self.turtle.dot(self.cell_size // 2) def display(self): """ Display the maze using Turtle graphics. """ if not self.turtle: import turtle self.turtle = turtle.Turtle() self.turtle.hideturtle() self.turtle.speed(0) self.turtle.penup() self.turtle.setheading(0) self.turtle.goto(0, 0) self.turtle.pendown() self.turtle.color('black') self.screen = self.turtle.getscreen() self.screen.setworldcoordinates(0, 0, self.width * self.cell_size, self.height * self.cell_size) for row in range(self.height): for col in range(self.width): if self.maze[row][col]: self._draw_wall(row, col) else: self._draw_path(row, col) self.screen.exitonclick() def solve(self, start=(0, 0), end=None): """ Solve the maze using the given start and end positions, and return a list of (row, col) tuples representing the solution path. Parameters: - start (tuple): a (row, col) tuple representing the starting position. Defaults to (0, 0). - end (tuple): a (row, col) tuple representing the ending position. Defaults to the bottom-right corner of the maze. Returns: - A list of (row, col) tuples representing the solution path. """ if not end: end = (self.height - 1, self.width - 1) queue = [(start, [start])] visited = set() while queue: (row, col), path = queue.pop(0) if (row, col) == end: return path if (row, col) in visited: continue visited.add((row, col)) if row > 0 and not self.maze[row - 1][col]: queue.append(((row - 1, col), path + [(row - 1, col)])) if row < self.height - 1 and not self.maze[row + 1][col]: queue.append(((row + 1, col), path + [(row + 1, col)])) if col > 0 and not self.maze[row][col - 1]: queue.append(((row, col - 1), path + [(row, col - 1)])) if col < self.width - 1 and not self.maze[row][col + 1]: queue.append(((row, col + 1), path + [(row, col + 1)])) return None ``` 以上就是 `freegames.maze` 模块的详细注释,希望能帮助你更好地理解它的实现和使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值