您的位置:首页 > 其它

百炼-2815-城堡问题-DFS

2015-07-21 10:23 323 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: