[hoj]Red and Black

来源:互联网 发布:软件win8升级win10 编辑:程序博客网 时间:2024/05/30 23:02

经典搜索题。

自己写了个DFS非递归实现。其实还是递归实现比较科学。

BFS用函数也比较好。主要是return方便,递归是进入方便。总之都是停止多重循环中的某一个状态。

/*This Code is Submitted by Iris for Problem 1797 at 2013-07-24 13:31:26*///DFS Stack#include <stack>#include <cstdio>using namespace std;int move[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};typedef struct point{    int x,y;}point;int main(){    int w,h;    while(scanf("%d %d",&w,&h)&&(w+h))    {        char t[25][25];        for(int i=0;i<h;i++)        {            scanf("%s",t[i]);        }        point p0;        int map[25][25];        for(int i=0;i<h;i++)            for(int j=0;j<w;j++)            {                if(t[i][j]=='.')    map[i][j] = 0;                else if(t[i][j]=='#')   map[i][j] = 1;                else{                    map[i][j] = 1;                    p0.x = i;                    p0.y = j;                }            }        stack<point> s;        s.push(p0);        int ans = 1,flag;        while(!s.empty())        {            //printf("*\n");            flag = 0;            point p;            p = s.top();            int tx,ty;            for(int i=0;i<4;i++)            {                tx = p.x + move[i][0];                ty = p.y + move[i][1];                if(tx>=0 && tx<h && ty>=0 && ty<w && !map[tx][ty])                {                    ans++;                    map[tx][ty] = 1;                    point tmp = {tx,ty};                    s.push(tmp);                    flag = 1;                    break;                }            }            if(!flag)//can't move            {                s.pop();            }        }        printf("%d\n",ans);    }    return 0;}