hdoj 1312 Red and Black 深度遍历的实现

来源:互联网 发布:淘宝买抱枕 编辑:程序博客网 时间:2024/06/07 14:56

题目大意:一个人站在一块黑色瓷砖上,他只能向四个方向走,不能走到红色瓷板上,求能走过的黑色瓷板,走过了的黑色瓷板不算

深度遍历,记录走过的格子

#include <iostream>#include <cstdio>#include <cstring>#include <queue>#include <climits>#include <algorithm>using namespace std;struct node{int x, y;};const int maxn = 25;char room[maxn][maxn];int w, h, ans;int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};void dfs(int x, int y);int main(){int sx, sy;while(true){scanf("%d %d", &w, &h);if(0 == w && 0 == h)break;for(int i = 0; i < h; i++){scanf("%s", room[i]);for(int j = 0; j < w; j++){if(room[i][j] == '@'){sx = i, sy = j;}}}ans = 0;dfs(sx, sy);printf("%d\n", ans);}return 0;}void dfs(int x, int y){int dx, dy;if(room[x][y] == '#')return;room[x][y] = '#';ans++;for(int i = 0; i < 4; i++){dx = x + dir[i][0];dy = y + dir[i][1];if(dx >= 0 && dx < h && dy >= 0 && dy < w)dfs(dx, dy);}}


原创粉丝点击