codeforces 377A Maze

简介: 点击打开cf377A 题意:给定一个n*m的地图,这个地图初始化有s个空地,并且这s个空地是连通的。现在要求找到一种方案放k个的墙到这个地图使得剩下的s-k个点还是连通的 思路:因为初始化的地图是一个连通的,要求s-k个点也是连通的。

点击打开cf377A


题意:给定一个n*m的地图,这个地图初始化有s个空地,并且这s个空地是连通的。现在要求找到一种方案放k个的墙到这个地图使得剩下的s-k个点还是连通的

思路:因为初始化的地图是一个连通的,要求s-k个点也是连通的。那么我们只要对这个图搜索到s-k个连通的点,然后剩下的k个点全部放墙就可以了

代码:

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 510;

int n , m , s , k;
char mat[MAXN][MAXN];
bool vis[MAXN][MAXN];
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};

bool isOk(int x , int y){
	if(x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && mat[x][y] == '.')
		return true;
    return false;	
}

void dfs(int x , int y){
	if(k == 0)
		return;
	k--;
	mat[x][y] = '1';
	for(int i = 0 ; i < 4 ; i++){
		int tx = x+dir[i][0];
		int ty = y+dir[i][1];
		if(isOk(tx,ty)){
			vis[tx][ty] = true;
			dfs(tx , ty);
		}
	}
}

void output(){
	for(int i = 0 ; i < n ; i++){
		for(int j = 0 ; j < m ; j++){
			if(mat[i][j] == '1')
				printf(".");
			else if(mat[i][j] == '.')
				printf("X");
			else
				printf("%c" , mat[i][j]);
		}
		puts("");
	}
}

void solve(){
	memset(vis , false , sizeof(vis));
	k = s-k;
	for(int i = 0 ; i < n ; i++){
		for(int j = 0 ; j < m ; j++){
			if(mat[i][j] == '.'){
				vis[i][j] = true;
				dfs(i , j);
				output();
				return;
			}
		}
	}
}

int main(){
	scanf("%d%d%d%*c" , &n , &m , &k);
	s = 0;
	for(int i = 0 ; i < n ; i++){
		gets(mat[i]);
		for(int j = 0 ; j < m ; j++)
			if(mat[i][j] == '.')
				s++;
	}
	solve();
	return 0;
}



目录
相关文章
|
7月前
codeforces 289 B. Polo the Penguin and Matrix
题目意思是在n*m的矩阵中,你可以对矩阵中的每个数加或者减d,求最少的操作次数,使得矩阵中所有的元素相同。 虽然在condeforces中被分到了dp一类,但完全可以通过排序,暴力的方法解决。
26 0
|
8月前
|
算法
POJ3061 Subsequence
POJ3061 Subsequence
CodeForces 377A-Maze(DFS找连通块)
CodeForces 377A-Maze(DFS找连通块)
CodeForces 377A-Maze(DFS找连通块)
|
测试技术
HDU-1026,Ignatius and the Princess I(BFS+打印路径)
HDU-1026,Ignatius and the Princess I(BFS+打印路径)
|
机器学习/深度学习 算法 人工智能
[LeetCode]--59. Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9
1130 0