题意:有个房间,房间的值用四面的门加起来的值表示,非常巧妙,西门用1表示,北门用2表示,东门用4表示,南门用8表示,最后判断是否连通的方法使用&,非常巧妙。
题解一:使用递归解法:
//递归实现
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=60;
int r,c,room[maxn][maxn],color[maxn][maxn],maxarea,temparea,colors;
void dfs(int row,int col)
{
if(color[row][col]){
return ;
}
color[row][col]=colors;
temparea++;
if((room[row][col]&1)==0){
dfs(row,col-1);
}
if((room[row][col]&2)==0){
dfs(row-1,col);
}
if((room[row][col]&4)==0){
dfs(row,col+1);
}
if((room[row][col]&8)==0){
dfs(row+1,col);
}
}
int main()
{
scanf("%d%d",&r,&c);
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
scanf("%d",&room[i][j]);
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(!color[i][j]){
temparea=0;
++colors;
dfs(i,j);
maxarea=max(maxarea,temparea);
}
}
}
printf("%d\n%d\n",colors,maxarea);
return 0;
}
题解二:使用栈实现
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=60;
int r,c,room[maxn][maxn],color[maxn][maxn],colors,maxarea,temparea;
typedef pair<int,int>PII;
void dfs(int row,int col)
{
stack<PII>s;
s.push(make_pair(row,col));
while(!s.empty()){
PII temp=s.top();
s.pop();
int x=temp.first,y=temp.second;
if(color[x][y]){
continue;
}
color[x][y]=colors;
temparea++;
if((room[x][y]&1)==0){
s.push(make_pair(x,y-1));
}
if((room[x][y]&2)==0){
s.push(make_pair(x-1,y));
}
if((room[x][y]&4)==0){
s.push(make_pair(x,y+1));
}
if((room[x][y]&8)==0){
s.push(make_pair(x+1,y));
}
}
}
int main()
{
scanf("%d%d",&r,&c);
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
scanf("%d",&room[i][j]);
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(!color[i][j]){
temparea=0;
colors++;
dfs(i,j);
maxarea=max(maxarea,temparea);
}
}
}
printf("%d\n%d\n",colors,maxarea);
return 0;
}