算法基础 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 ;
}
“`