迷宫问题(唯一路径)

#include<iostream> using namespace std; const int MAX = 100; int maze[MAX][MAX]; int path[MAX][MAX]; int startRow,startCol; int endRow,endCol; bool flag = false; int x[] = {-1,0,1,0};//up right down left int y[] = {0,1,0,-1}; //唯一路径解法 bool dfs(int sx,int sy,int n) { maze[sx][sy] = 1; if(sx==n && sy==n) flag = true; for(int i=0;i<4;i++) { if(flag==false && maze[sx+x[i]][sy+y[i]]==0) dfs(sx+x[i],sy+y[i],n); } if(flag==false)//由于只有到达出口的路径为正确路径,当递归返回时再将maze[i][j]置为零 maze[sx][sy] = 0; return flag; } void initMaze(int n) { int i,j; for(i=0;i<=n+1;i++) { for(j=0;j<=n+1;j++) cin >> maze[i][j]; } } int main() { int n; while(cin >> n) { initMaze(n); cout << “show path” << endl; int i,j; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(maze[i][j]==2) cout << 1 << ” “; else cout << 0 << ” “; } cout << endl; } if(dfs(1,1,n)) { for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(maze[i][j]==1) cout << 1 << ” “; else cout << ” “; } cout << endl; } } else cout << “no path” << endl; } return 0; }

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/custqi/article/details/6455428
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞