HDU 1312 Red and Black (DFS & BFS)

时间:2023-03-09 08:31:57
HDU 1312 Red and Black (DFS & BFS)

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312

题目大意:有一间矩形房屋,地上铺了红、黑两种颜色的方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动,计算你总共能够到达多少块黑色的瓷砖。

要求:输入包含多组数据,每组数据的第一行输入的是两个整数 W 和 H, 分别表示 x 方向与 y 方向上的瓷砖数量,并且 W 和 H 都不超过20。在接下来的 H 行中,每行包含 W 个字符,每个字符表示一块瓷砖的颜色,规则如下:

' . ' 代表黑色的瓷砖

          ' # '代表白色的瓷砖

          ' @ ' 代表黑色的瓷砖,并且你站在这块瓷砖上,该字符在每个数据集合中唯一出现一次。

当在一行中读入的是两个零时,表示输入结束。

对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。

思路:这道题算是一道比较典型的 DFS 题,但也可以用 BFS 做出来。

代码:

  DFS

#include <iostream>
#include <cstring>
using namespace std;
#define clr(a) memset(a,0,sizeof(a)) const int MAXN = 25;
int dir[2][4]={1, -1 , 0, 0, 0, 0, 1, -1};
int w, h, ans, sx, sy;
int mp[MAXN][MAXN];
char s[MAXN][MAXN]; int DFS(int x,int y){
mp[x][y] = 1;
for(int i=0;i<4;i++){
int dx = x + dir[0][i];
int dy = y + dir[1][i]; if (dx >= 0 && dy >= 0 && dy < w && dx < h &&
s[dx][dy] == '.' && !mp[dx][dy]) {
ans++;
DFS(dx, dy);
}
}
return ans;
} int main() {
while (scanf("%d %d", &w, &h) != EOF) {
if (w == 0 && h == 0) break;
clr(mp); for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> s[i][j];
if (s[i][j] == '@') {
sx = i;
sy = j;
}
}
}
ans = 1;
cout << DFS(sx, sy) << endl;
} return 0;
}

BFS (使用 广搜时可以把搜索过的地方用 ' # ' 进行标记)

#include <iostream>
#include <queue>
using namespace std; const int N = 25;
int w, h, sx, sy, ans;
char s[N][N];
int d[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; struct node {
int x, y;
}; void bfs() {
node start, end;
queue<node> q; start.x = sx;
start.y = sy;
q.push(start); while (!q.empty()) {
start = q.front();
q.pop(); for (int i = 0; i < 4; i++) {
end.x = start.x + d[i][0];
end.y = start.y + d[i][1]; if (end.x >= 0 && end.y >= 0 && end.y < w && end.x < h &&
s[end.x][end.y] == '.' ) {
ans++;
s[end.x][end.y] = '#';
q.push(end);
}
}
}
} int main() {
while (cin >> w >> h) {
if (w == 0 && h == 0) break; for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++) {
cin >> s[i][j];
if (s[i][j] == '@') {
sx = i;
sy = j;
}
} ans = 1;
bfs();
cout << ans << endl;
}
return 0;
}