5 4 1 1 0 0 1 1 1 1 0 1 1 0 1 1 0 1 1 1 1 1 1 1 5 4
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4) (1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4) (1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4) (1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4) (1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4) (1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4) (1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
深搜+模拟,注意当前递归栈的visited标志使用过后要重置回来,还有要注意题目中“左上右下的顺序”...
#include <iostream> //#include <fstream> using namespace std; const int MAXN = 16; const int devide = 100; int maze[MAXN][MAXN]; int queue[MAXN*MAXN]; int visited[MAXN][MAXN]; int m,n,r,s; int flag; void dfs(const int& x,const int& y,const int& depth) { if(x == r && y == s) { if(!flag) flag = 1; for(int i = 0;i < depth;i ++) { int u = queue[i]; cout<<"("<<u/devide<<","<<u%devide<<")->"; } cout<<"("<<x<<","<<y<<")"<<endl; } else { int p = queue[depth] / devide; int q = queue[depth] % devide; //左上右下 if(q - 1 > 0 && maze[p][q-1] && !visited[p][q-1]) { queue[depth + 1] = p * devide + q - 1; visited[p][q - 1] = 1; dfs(p,q - 1,depth + 1); visited[p][q - 1] = 0; } if(p - 1 > 0 && maze[p-1][q] && !visited[p-1][q]) { queue[depth + 1] = (p - 1) * devide + q; visited[p-1][q] = 1; dfs(p-1,q,depth+1); visited[p-1][q] = 0; } if(q + 1 <= n && maze[p][q+1] && !visited[p][q+1]) { queue[depth + 1] = p * devide + q + 1; visited[p][q+1] = 1; dfs(p,q+1,depth + 1); visited[p][q+1] = 0; } if(p + 1 <= m && maze[p+1][q] && !visited[p+1][q]) { queue[depth + 1] = (p + 1) * devide + q; visited[p+1][q] = 1; dfs(p+1,q,depth+1); visited[p+1][q] = 0; } } } int main() { //ifstream cin("in.txt"); cin>>m>>n; for(int i = 1;i <= m;i ++) for(int j = 1;j <= n;j ++) cin>>maze[i][j]; int x,y; cin>>x>>y>>r>>s; queue[0] = x * devide + y; visited[x][y] = 1; dfs(x,y,0); if(!flag) cout<<-1<<endl; return 0; }