走迷宫问题算法 :
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<climits>
using namespace std ;
typedef pair<int,int> PII ;
const int N = 1010 ;
int n , x1 , y1 , x2 , y2 ;
int maze[N][N] ;
int minLength = INT_MAX , pathCount ;
vector<PII>path ;
int st[N][N] ;
int dx[] = {-1 , 1 , 0 , 0 } , dy[] = { 0 , 0 , -1 , 1} ;
void dfs (int x , int y)
{
if (x == x2 && y == y2) {
pathCount++ ;
for (int i = 0 ; i < path.size() ; i++) {
int x0 = path[i].first , y0 = path[i].second ;
cout << "(" << x0 << "," << y0 << ")" << " " ;
}
puts ("") ;
if (minLength > path.size()) minLength = path.size() ;
return ;
}
for (int i = 0 ; i < 4 ; i++ ){
int x0 = x + dx[i] , y0 = y + dy[i] ;
if (x0 >= 1 && x0 <= n && y0 >= 1 && y0 <= n && st[x0][y0] == 0 && maze[x0][y0] == 0){
path.push_back({x0 , y0}) ;
st[x0][y0] = 1 ;
dfs (x0 , y0) ;
st[x0][y0] = 0 ;
path.pop_back() ;
}
}
}
int main ()
{
cout << "请输入迷宫的维数: " ;
cin >> n ;
cout << "请输入迷宫的起点 : " ;
cin >> x1 >> y1 ;
cout << "请输入迷宫的终点 : " ;
cin >> x2 >> y2 ;
cout << "请输入迷宫 : " << endl ;
for (int i = 0 ; i < n ; i++)
for (int j = 0 ; j < n ; j++) scanf ("%d" , &maze[i][j]) ;
path.push_back({x1 , y1}) ;
st[x1][y1] = 1 ;
dfs (x1 , y1) ;
cout << pathCount << " " << minLength << endl ;
return 0 ;
}