POJ 1111 Image Perimeters

来源:互联网 发布:软件项目阶段总结报告 编辑:程序博客网 时间:2024/05/17 18:13

1. 写得最有逻辑的一道题了,10次讲座学的最好的就是DFS和BFS了。

2. 直接深搜

#include <iostream>#include <fstream>#include <string>#include <algorithm>#include <cstring>#include <stack>#include <queue>#include <climits>#include <cstdio>#include <cmath>using namespace std;int a, b, sx, sy;char map[25][25];int num[25][25];bool flag[25][25];int dir[8][2] = {{-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}};bool check(int x, int y){    return (x > 0 && x <= a && y > 0 && y <= b) ? true : false;}void dfs(int x, int y){    int nextx, nexty;    flag[x][y] = 1;    for (int i = 0; i < 8; i++)    {        nextx = x + dir[i][0];        nexty = y + dir[i][1];        if ((dir[i][0] == 0 || dir[i][1] == 0) && map[nextx][nexty] != 'X')            num[x][y]++;        if (check(nextx, nexty) && map[nextx][nexty] == 'X' && flag[nextx][nexty] == 0)            dfs(nextx, nexty);    }}void init(){    for (int i = 0; i < 25; i++)        for (int j = 0; j < 25; j++)            map[i][j] = '.';    memset(num, 0, sizeof(num));    memset(flag, 0, sizeof(flag));}int main(){    int i, j, ans;    while (cin >> a >> b >> sx >> sy)    {        if (!a && !b)            break;        init();        for (i = 1; i <= a; i++)            for (j = 1; j <= b; j++)                cin >> map[i][j];        dfs(sx, sy);        ans = 0;        for (i = 1; i <= a; i++)            for (j = 1; j <= b; j++)                ans += num[i][j];        cout << ans << endl;    }    return 0;}


原创粉丝点击