深度优先搜索:
原理:利用迭代枚举出所有数据
问题:1.minn给一个很大的初值:因为第一个到达的路线的step必须小于他才能给minn赋值
2.利用方向数组next[4][2]加上for循环表示了往4个方向枚举;
3.因为初学的缘故没有意识到规范问题,需要用a[][]来储存地图,直接都用存已经走过路径的book[]一起来储存地图,虽然暂时可以达到效果,但不利于之后的解题
#include <iostream>
using namespace std;
int endx, endy;
int m, n;
int book[100][100];
int minn=9999999;//给一个很大的初始值;
void dfs(int x, int y, int step) {
int next[4][2] = {
{0,1},//右边
{1,0},//下
{0,-1},//左边
{-1,0}//上
};//方向数组
if (endx == x && endy == y) {
if (minn > step) {
minn = step;
}
return;
}
int tx, ty;//下一步的x,y
for (int i = 0; i < 4; i++) {
tx = x + next[i][0];
ty = y + next[i][1];
if (tx<1 || ty<1 || tx>m || ty>n) {
continue;
}
//if(tx!=endx||ty!=endy)对吧他一定是有走到终点那一步进入了再判断走到了终点这里是判断路径和障碍物
if (book[tx][ty] == 0) {
book[tx][ty] = 1;
dfs(tx, ty, step + 1);
book[tx][ty] = 0;
}
}
return;
}
int main()
{
cin >> m >> n;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> book[i][j];
}
}
//for (int i = 1; i <= m; i++) {
// for (int j = 1; j <= n; j++) {
// cout << book[i][j]<<" ";
// }
// cout << endl;
//}
int startx, starty;
cin >> startx >> starty;
cin >> endx >> endy;
book[startx][starty] = 1;//
dfs(startx, starty, 0);
cout << minn;
return 0;
}
//测试样例
//5 4
//0 0 1 0
//0 0 0 0
//0 0 1 0
//0 1 0 0
//0 0 0 1
//1 1 4 3
广度优先搜索:
先自定义一个结构体struct node{
int x;int y;int step;
}
再·通过自己定义的一个que[]队列
来实现优先搜索找到目的地
问题:
1.为什么数组要开51,2051因为我是最大上限为50个但是我每一个数组都是从1开始便于自己理解和梳理,tail和head都是从1开始。
2.最后输出的时候tail要-1,因为tail是指向最后一个数的后面那个空白处。如上图,指向2的后面那个空白处
3.
采用了自定义一个flag来实现找到了正确结果从而跳出for和while循环
4.for循环结束后一定要有一个head++,来找到新的开始点。
5.
一开始自作聪明后面发现改变了。
#include <iostream>
using namespace std;
struct node {
int x;
int y;
int s;
int f;
};
int main()
{
int a[51][51];
int m, n;
cin >> m >> n;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
}
}
struct node que[2501];//第一个是不要的
int head = 1;
int tail = 1;
int book[51][51] = {0};
int next[4][2] = {
{0,1},{1,0},{0,-1}, {-1,0}
};
int startx, starty;
//cout << "请输入开始坐标" << endl;
cin >> startx >> starty;
//cout << "请输入终点" << endl;
int endx, endy;
cin >> endx>>endy;
que[head].x = startx ;
que[head].y = starty ;
que[head].s = 0;
tail++;
int tx, ty;
int flag=0;
while (head < tail) {
for (int i = 0; i < 4; i++) {
tx = que[head].x + next[i][0];
ty = que[head].y + next[i][1];
if (tx<1 || ty<1 || tx>m || ty>n) {
continue;
}
if (a[tx][ty] == 0 && book[tx][ty] == 0){
que[tail].x = tx;
que[tail].y = ty;
que[tail].s = que[head].s + 1;
book[tx][ty] = 1;
que[tail].f = head;
tail++;
if (tx == endx && ty == endy) {
flag = 1;
break;
}
}
}
head++;
if (flag == 1) {
break;
}
}
cout << "最短路径:" << que[tail - 1].s << endl;
cout << "路线" << endl;
tail--;
//for (int i = 0; i < que[tail].s; i++) {
// cout << que[tail].x << "," << que[tail].y << endl;
// tail = que[tail].f;
//}//因为第二次循环过来que[tail]改变了不是一个常量了
int j = que[tail].s;
for (int i = 0; i < j; i++) {
cout << que[tail].x << "," << que[tail].y << endl;
tail = que[tail].f;
}
return 0;
}