#include<stdio.h>
#include<stack>
#include<stdlib.h>
using namespace std;
typedef struct{
int x;
int y;
}node;
node end;
stack<int> s;
int map[102][102];
int dfs[102][102];
bool ifroad(node parent){
if(!map[parent.x][parent.y]) return 1;
return 0;
}
void show(stack<int> s){
char x;
stack<char> answer;
while(!s.empty()){
switch (s.top()){
case 1:{
x='D';
break;
}
case 2:{
x='L';
break;
}
case 3:{
x='R';
break;
}
case 4:{
x='U';
break;
}
}
answer.push(x);
s.pop();
}
while(!answer.empty()){
printf("%c",answer.top());
answer.pop();
}
putchar('\n');
}
int DFS(node x){
node child;
if(x.x==end.x&&x.y==end.y){
show(s);
}
else{
for(int i=1;i<=4;i++){
child.x=x.x;
child.y=x.y;
switch (i){
case 1:{
child.x++;
break;
}
case 2:{
child.y--;
break;
}
case 3:{
child.y++;
break;
}
case 4:{
child.x--;
break;
}
}
if(ifroad(child)&&!dfs[child.x][child.y]){
// printf("int %d ",i);
s.push(i);
dfs[child.x][child.y]=1;
DFS(child);
}
}
}
if(!s.empty()){
//int out=s.top(); printf("\nout %d ",out);
s.pop();
dfs[x.x][x.y]=0;
}
}
int main(){
char x;
node start;
int n,m;
do{
puts("迷宫大小(行 列):");
scanf("%d %d",&n,&m);
puts("起点(行 列):");
scanf("%d %d",&start.x,&start.y);
puts("终点(行 列):");
scanf("%d %d",&end.x,&end.y);
puts("0路1墙输入迷宫:");
for(int i=0;i<=n+1;i++){
map[i][0]=1;
map[i][m+1]=1;
}
for(int i=0;i<=m+1;i++){
map[0][i]=1;
map[n+1][i]=1;
}
for(int x=1;x<=n;x++){
for(int y=1;y<=m;y++){
dfs[x][y]=0;
}
}
for(int x=1;x<=n;x++){
for(int y=1;y<=m;y++){
scanf("%d",&map[x][y]);
}
}
dfs[start.x][start.y]=1;
DFS(start);
getchar();
puts("\n输入任意键继续,输入ctrl+b退出\n");
}while(scanf("%c",&x)!=EOF);
}
图论 / 深度优先搜索----迷宫程序
最新推荐文章于 2019-11-03 13:38:50 发布