算法03|搜索

深度搜索模型;

1
2
3
4
5
6
7
8
void bfs (int step)
{
for(i=1;i<=n;i++)
{
dfs(step+1);
}
return;
}

迷宫问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
//迷宫问题
int n,m,p,q,min=99999999;
int a[51][51],book[51][51];
void dfs(int x,int y,int step)
{
int next[4][2] = {
{0,1},{1,0},{0,-1},{-1,0}
};
int tx,ty,k;
if (x==p && y==q) {
if (step<min)
min = step;
return ;
}
for(k=0;k<=3;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
if (tx<1 || tx>n || ty<1 || ty>m)
continue;
//判断该点是否成为障碍物或者已经在路径中
if(a[tx][ty]==0 && book[tx][ty]==0)
{
book[tx][ty]=1;
dfs(tx, ty, step+1);
book[tx][ty]=0;
}
}return;
}
int main()
{
int i,j,startx,starty;
scanf("%d %d",&n,&m);
for(i=1;i<n;i++)
for(j=1;j<=m;j++)
scanf("%d",&a[i][j]);
scanf("%d %d %d",&startx,&starty,&p,&q);
book[startx][startx]=1;
dfs(startx, starty, 0);
printf("%d",min);
getchar();getchar();
return 0;
}
文章目录
  1. 1. 深度搜索模型;
  2. 2. 迷宫问题
|