各大公司数据结构与算法面试题解答(二)

来源:互联网 发布:皮衣品牌 知乎 编辑:程序博客网 时间:2024/06/10 15:38

6寻找迷宫的一条出路,1代表障碍,0代表通。

算法描述:

这里可以使用几种方法,我知道的有使用《数据结构》上“穷举求解”的方法,还有就是使用遗传算法寻找最优路径。这里我先简单描述下“穷举求解”,然后再做遗传算法的方式。

1 问题中要涉及走过路径的回溯,因为栈是先进后出,所以利于回溯,选择栈来存储走过路径

2 每一步有四个方向可以走,每到一步依次判断每一个方向,只要判断到某个方向可走就选择这个方向前进。

3 当所有方向都不能行进时,回溯到上一步,此时判断栈顶指针是否为-1,如果是,返回false失败,否则递归调用继续寻找。

C++源码:

#include "stdafx.h"#include <stdio.h>#include <iostream>using namespace std;#define MAX_SIZE 10int maze[MAX_SIZE][MAX_SIZE]={{1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},{1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}};typedef struct{int x;int y;}POINT;typedef struct{POINT data[MAX_SIZE*MAX_SIZE];int top;}STACK;bool operator != (POINT& point1,POINT& point2){if(point1.x!=point2.x||point1.y!=point2.y)return true;elsereturn false;}bool operator == (POINT& point1,POINT& point2){if(point1.x==point2.x&&point1.y==point2.y)return true;elsereturn false;}bool FindWay(int maze[][MAX_SIZE],POINT start,POINT end,STACK& way){POINT step;step.x = start.x;step.y = start.y;if(way.data[way.top]!=end){/************first,make sure the direction**********/if(maze[step.y][step.x+1]==0)//east{maze[step.y][step.x] = 1;way.top++;way.data[way.top] = step;step.x++;FindWay(maze,step,end,way);}else if(maze[step.y+1][step.x]==0)//south{maze[step.y][step.x] = 1;way.top++;way.data[way.top] = step;step.y++;FindWay(maze,step,end,way);}else if(maze[step.y][step.x-1]==0)//west{maze[step.y][step.x] = 1;way.top++;way.data[way.top] = step;step.x--;FindWay(maze,step,end,way);}else if(maze[step.y-1][step.x]==0)//north{maze[step.y][step.x] = 1;way.top++;way.data[way.top] = step;step.y--;FindWay(maze,step,end,way);}else//There is no direction available{if(way.top<0)return false;else{maze[step.y][step.x] = 1;step = way.data[way.top];way.top--;FindWay(maze,step,end,way);}}//end else}//end ifelsereturn true;}int main(int argc, char* argv[]){POINT start,end;start.x = 1;start.y = 1;end.x = 8;end.y = 8;STACK way;way.top = -1;if(FindWay(maze,start,end,way)){cout<<"Have found the way!"<<endl;for(int i=0;i<=way.top;i++)printf("(%d,%d)  ",way.data[i].x,way.data[i].y);}elsecout<<"Don't find the way!"<<endl;return 1;}

运行结果:


原创粉丝点击