题目链接:http://bailian.openjudge.cn/practice/2815/
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<vector>
#include<algorithm>
#define LL long long
using namespace std;
int r,c;
int rooms[60][60];
int color[60][60]; // 标记染色;
struct room{int r,c;room(int rr=0,int cc=0):r(rr),c(cc){} };
int roomArea=0,maxArea=0,roomNum=0;
/*
void dfs(int r,int c) // 用栈写递归,可以解决用递归爆栈的问题,递归其实就是用栈实现的;
{
stack<room> stk;
stk.push(room(r,c));
while(!stk.empty()){
room rm=stk.top();
r=rm.r,c=rm.c;
if(color[r][c]) stk.pop(); // 只有访问到标记的点才将他pop,否则会WA,因为有四个方向要走;
else{
++roomArea;
color[r][c]=roomNum;
if((rooms[r][c]&1)==0) stk.push(room(r,c-1)); // 向西走
if((rooms[r][c]&2)==0) stk.push(room(r-1,c)); // 向北走
if((rooms[r][c]&4)==0) stk.push(room(r,c+1)); // 向东走
if((rooms[r][c]&8)==0) stk.push(room(r+1,c)); // 向南走
}
}
}*/
// 用递归解决方案;
void dfs(int i,int j)
{
if(color[i][j]) return;
++roomArea;
color[i][j]=roomNum;
if((rooms[i][j]&1)==0) dfs(i,j-1); // 向西走
if((rooms[i][j]&2)==0) dfs(i-1,j); // 向北走
if((rooms[i][j]&4)==0) dfs(i,j+1); // 向东走
if((rooms[i][j]&8)==0) dfs(i+1,j); // 向南走
}
int main()
{
while(~scanf("%d%d",&r,&c)){
maxArea=0,roomNum=0;
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
scanf("%d",&rooms[i][j]);
}
}
memset(color,0,sizeof(color));
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
if(!color[i][j]){
++roomNum, roomArea=0;
dfs(i,j);
maxArea=max(maxArea,roomArea);
}
}
}
printf("%d\n%d\n",roomNum,maxArea);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wlxsq/article/details/46981965