现在的位置: 首页 > 综合 > 正文

ural 1033. Labyrinth(dfs)

2012年12月29日 ⁄ 综合 ⁄ 共 794字 ⁄ 字号 评论关闭

题目链接http://acm.timus.ru/problem.aspx?space=1&num=1033

唯一注意的就是当图不连通时两个角都要搜索,搜索的总和才是最终答案。

#include <iostream>
#include <cstdio>
#include <cstring>
int n, num;
char map[34][34];
bool visited[34][34] = {0};
int dir[4][2] = {{-1,0}, {0,1}, {1,0}, {0,-1}};
void dfs(int x, int y)
{
    if ((x==0 && y>0 && y<n-1) || (y==0 && x>0 && x<n-1) || (x==n-1 && y>0 && y<n-1)
            || (y==n-1 && x>0 && x<n-1))                              //边上非角的墙
        ++num;
    if ((x==0 && y==n-1) || (y==0 && x==n-1))                                             //两个角的需要两张
        num += 2;
    visited[x][y] = 1;
    for (int i = 0; i < 4; ++i)
    {
        int fx = x + dir[i][0];
        int fy = y + dir[i][1];
        if (fx>=0 && fx<n && fy>=0 && fy<n && !visited[fx][fy])
        {
            if (map[fx][fy] == '#')
                ++num;
            else
                dfs(fx, fy);
        }
    }
}
int main()
{
    std::cin >> n;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            std::cin >> map[i][j];
    num = 0;
    dfs(0, 0);
    if (!visited[n-1][n-1])                            //没有访问过另一个角则都搜索
        dfs(n-1, n-1);
    printf("%d\n", num * 9);
    return 0;
}

 

抱歉!评论已关闭.