迷宫找最短路径 深度优先—C

从迷宫的起点到终点的最短路径,用深度优先搜索

#include<stdio.h>
int n,m,p,q,min=99999999;
int a[100][100],book[100][100];
void dfs(int x,int y,int step)
{
    int tx,ty,k ;
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
    if(x==p&&y==q)
    {
        if(min>step)
            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%d",&startx,&starty,&p,&q);
    book[startx][starty]=1;
    dfs(startx,starty,0);//步数也带上作为参数
    //输出最短步数
    printf("%d",min);
    return 0;


}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用深度优先搜索算法迷宫最短路径不是很常见,因为它并不保证能最短路径。不过,以下是使用深度优先搜索算法迷宫路径的C语言代码示例: ```c #include <stdio.h> #include <stdlib.h> #define ROW 6 // 迷宫行数 #define COL 6 // 迷宫列数 // 迷宫地图 int maze[ROW][COL] = { {0, 0, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 1}, {0, 1, 0, 1, 0, 0}, {0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0} }; // 记录迷宫中每个位置是否被访问过 int visited[ROW][COL] = {0}; // 记录每个位置的前一个位置 int pre[ROW][COL][2] = {0}; // 判断是否到达终点 int isEnd(int row, int col) { return row == ROW-1 && col == COL-1; } // 判断某个位置是否可以走 int canMove(int row, int col) { return row >= 0 && row < ROW && col >= 0 && col < COL && maze[row][col] == 0 && visited[row][col] == 0; } // 深度优先搜索 void dfs(int row, int col) { // 标记为已访问 visited[row][col] = 1; // 判断是否到达终点 if (isEnd(row, col)) { return; } // 尝试向上走 if (canMove(row-1, col)) { pre[row-1][col][0] = row; pre[row-1][col][1] = col; dfs(row-1, col); } // 尝试向下走 if (canMove(row+1, col)) { pre[row+1][col][0] = row; pre[row+1][col][1] = col; dfs(row+1, col); } // 尝试向左走 if (canMove(row, col-1)) { pre[row][col-1][0] = row; pre[row][col-1][1] = col; dfs(row, col-1); } // 尝试向右走 if (canMove(row, col+1)) { pre[row][col+1][0] = row; pre[row][col+1][1] = col; dfs(row, col+1); } } // 打印路径 void printPath() { int row = ROW-1, col = COL-1; printf("Path: (%d, %d)", row, col); while (row != 0 || col != 0) { int temp_row = row, temp_col = col; row = pre[temp_row][temp_col][0]; col = pre[temp_row][temp_col][1]; printf(" -> (%d, %d)", row, col); } printf("\n"); } int main() { dfs(0, 0); printPath(); return 0; } ``` 该算法使用递归来实现深度优先搜索。从起点开始,每次尝试向上、下、左、右四个方向走,如果某个方向可以走,则标记该位置为已访问,并递归地访问该位置。当到达终点时,递归回溯到上一个位置,继续尝试其他方向。在访问每个位置时,记录它的前一个位置,最后通过前一个位置数组来构造出路径。需要注意的是,该算法不保证能最短路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值