问题描述:
给定一个大小为N*M的迷宫,每一步可以走上下左右四个方向,假设一定可以到到达终点,求达到终点的最小步数
输入:
S为起点,G为终点
思路:
使用深入优先搜索的方法
代码:
# include <iostream> # include <fstream> using namespace std; int N, M; char map[100][100]; int isUsed[100][100] = {0}; int DFS_Search(int i, int j) { isUsed[i][j] = 1; if ( map[i][j] == 'G' ) { return 0; } else { int MinDistance = 9999; if ( i - 1 >= 0 && map[i-1][j] != '#' && isUsed[i-1][j] == 0) { int dis = DFS_Search(i-1, j) + 1; MinDistance = dis < MinDistance ? dis : MinDistance; } if ( i + 1 <= N - 1 && map[i+1][j] != '#' && isUsed[i+1][j] == 0) { int dis = DFS_Search(i+1, j) + 1; MinDistance = dis < MinDistance ? dis : MinDistance; } if ( j - 1 >= 0 && map[i][j-1] != '#' && isUsed[i][j-1] == 0) { int dis = DFS_Search(i, j-1) + 1; MinDistance = dis < MinDistance ? dis : MinDistance; } if ( j + 1 <= M - 1 && map[i][j+1] != '#' && isUsed[i][j+1] == 0) { int dis = DFS_Search(i, j+1) + 1; MinDistance = dis < MinDistance ? dis : MinDistance; } return MinDistance; } } int main() { ifstream cin("MiGong_Data.txt"); cin>>N>>M; for ( int i = 0; i < N; i++) { for ( int j = 0; j < M; j++) { cin>>map[i][j]; } } int result = DFS_Search(0, 1); cout<<result<<endl; return 0; }