例题:百练2815 城堡问题

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;

int R, C;// 行列
int rooms[60][60];
int color[60][60];//房间是否染色过
int maxRoomArea = 0, roomNum = 0;
int roomArea;
struct Room{
	int r, c;
	Room(int rr, int cc):r(rr), c(cc) {}  //初始化, 类似class的构造函数 
};
/*//方法1:递归 
void dfs(int x, int y) {  // 递归 
	if(color[x][y]) return;
	color[x][y] = 1;
	++roomArea;
	color[x][y] = roomNum;
	if((rooms[x][y] & 1) == 0) dfs(x, y-1);//向西
	if((rooms[x][y] & 2) == 0) dfs(x-1, y);//向北
	if((rooms[x][y] & 4) == 0) dfs(x, y+1);//向东
	if((rooms[x][y] & 8) == 0) dfs(x+1, y);//向南
}
*/

//方法2:用栈 
void dfs(int r, int c) {
	stack<Room> stk;
	stk.push(Room(r, c));  // Room赋初值r,c, 返回一个结构体变量   真6! //居然还可以这么玩 
	while(!stk.empty()) {
		Room rm = stk.top();
		int i = rm.r; 
		int j = rm.c;
		if(color[i][j]) stk.pop();//如果已经访问过了 
		else {
			++ roomArea;
			color[i][j] = roomNum;
			if((rooms[i][j] & 1) == 0) stk.push(Room(i, j-1)); //西
			if((rooms[i][j] & 2) == 0) stk.push(Room(i-1, j)); //北
			if((rooms[i][j] & 4) == 0) stk.push(Room(i, j+1)); //东
			if((rooms[i][j] & 8) == 0) stk.push(Room(i+1, j)); //南 
		} 
	}
	
}



int main() {
	cin >> R >> C;
	for(int i = 0; i < R; i++)
		for(int j = 0; j < C; j++)
			cin >> rooms[i][j];
	memset(color, 0, sizeof(color));
	for(int i = 0; i < R; i++)
		for(int j = 0; j < C; j++)
			if(!color[i][j]) {
				++ roomNum;
				roomArea = 0;
				dfs(i, j);
				maxRoomArea = max(roomArea, maxRoomArea);
			}
	cout << roomNum << endl;
	cout << maxRoomArea << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值