您的位置:首页 > 其它

CodeForces 377A - maze

2016-02-17 10:08 357 查看
                                                                                A. Maze
点击打开链接

Pavel loves grid mazes. A grid maze is an
n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.

Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly
k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

Input
The first line contains three integers
n, m,
k (1 ≤ n, m ≤ 500,
0 ≤ k < s), where
n and m are the maze's height and width, correspondingly,
k is the number of walls Pavel wants to add and letter
s represents the number of empty cells in the original maze.

Each of the next n lines contains
m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#",
then the cell is a wall.

Output
Print n lines containing
m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is,
"." and "#").

It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

题目大意:主人公嫌弃空格太多,想空格少一点;注意的就是没有变化之前,所有空格都是连通的,变化之后所有空格还得是;连通的。思考一下是不是就会想到深搜呢,始终变化的是最后一个空格,所以变化之后,所有空格还是连通的咯,具体看下面代码。

代码:#include<iostream>
#include<cstring>
using namespace std;

char maze[505][505];
int sign[505][505];
int n,m,k;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

void dfs(int x,int y)
{
    if(k<=0 || x<0 || x >=n || y<0 || y>=m)return;
    if(maze[x][y] != '.' || sign[x][y]) return;
    sign[x][y] = 1;
    for(int i = 0;i < 4;i++)
    {
        int dx = x + dir[i][0];
        int dy = y + dir[i][1];
        dfs(dx,dy);
    }
    if(k) {maze[x][y] = 'X';k--;}

}
int main()
{
    while(cin>>n>>m>>k)
    {
        int i,j;
        memset(sign,0,sizeof(sign));
        for(i = 0;i < n;i++)
            cin>>maze[i];
        for(i = 0;i < n && k;i++)
        {
            for(j = 0;j< m && k;j++)
                dfs(i,j);
        }
        for(i = 0;i < n;i++)
            cout<<maze[i]<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: