HDU1312 ZOJ2165 Red and Black

HDU1312 ZOJ2165 Red and Black

问题链接:HDU1312 ZOJ2165 Red and Black

本题可以使用深度优先搜索求解。

这个程序说明如下:

1.方向数组 使用方向数组后,各个方向的试探的程序就会变得简洁了,用循环处理即可。

2.避免重复搜索 将搜索过的节点设置为“#”(墙),可以避免重复搜索,能够简化程序逻辑。

3.设置边界 通过设置边界,可以免去矩阵(二维数组)的边界判断,简化了程序逻辑。

该问题与图遍历中寻找联通块问题基本上是同构的,算法思路一致。

每当找到一个可以到达的点,只需要计数加一,并且使用DFS算法把与其相邻的4个可以到达的点擦除即可(避免重复计数)。

这个程序是拷贝HDU1241 UVa572 Oil Deposits修改实现的,分分钟的事情。

AC的C语言程序如下:

/* HDU1312 ZOJ2165 Red and Black */

#include <stdio.h>
#include <memory.h>

#define DIRECTSIZE 4

struct direct {
    int drow;
    int dcol;
} direct[DIRECTSIZE] =
    {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

#define MAXN 20

char grid[MAXN+2][MAXN+2];

int count;

void dfs(int row, int col)
{
    int i;

    for(i=0; i<DIRECTSIZE; i++) {
        int nextrow = row + direct[i].drow;
        int nextcol = col + direct[i].dcol;

        if(grid[nextrow][nextcol] == '.') {
            count++;

            grid[nextrow][nextcol] = '#';

            dfs(nextrow, nextcol);
        }
    }
}

int main(void)
{
    int x, y, i, j;

    while(scanf("%d%d", &y, &x) != EOF) {
        // 判定结束条件
        if(x == 0 && y == 0)
            break;

        // 清零:边界清零
        memset(grid, 0, sizeof(grid));

        // 读入数据
        for(i=1; i<=x; i++)
            scanf("%s", grid[i]+1);

        // 计数清零
        count = 0;

        // 深度优先搜索
        for(i=1; i<=x; i++)
            for(j=1; j<=y; j++)
                if(grid[i][j] == '@') {
                    count++;
                    dfs(i, j);
                }

        // 输出结果
        printf("%d
", count);
    }

    return 0;
}