您的位置:首页 > 其它

HDU 1312 DFS

2016-07-22 21:37 302 查看
算法基础 DFS 深度搜索hdu1312 Red and Black下面是题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1312

这道题的题意大致是你在@点处,’.’是能走的,’#’是不能走的,然后问你能走过的最多的’.’的步数。典型的DFS题目。

```
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std ;
int sx, sy;
char maze[100][100];
int n, m; //迷宫的长和宽
int ans; // 最终走的步数
int dirt[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
void dfs(int x, int y)
{
if(x < 0 || x >= n || y < 0 || y >= m) return ;
if(maze[x][y] == '#') return ;
ans++;
for(int i = 0 ; i < 4 ; i++){
int tx = x + dirt[i][0];
int ty = y + dirt[i][1];
maze[x][y] = '#';//每走过一个'.'就吧它标记为不能走的'#'然后ans就会加一
dfs(tx, ty);
}
}

int main()
{

while(cin >> m >> n && (n||m)){
ans = 0 ;
for(int i = 0 ; i < n ; i++)
cin >> maze[i];
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
//scanf("%s", &maze[i][j]);
if(maze[i][j] == '@')
sx = i , sy = j ;
}
}
dfs(sx, sy);
cout << ans << endl;
}
system("pause");
return 0 ;
}


“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 搜索 dfs