数据结构实验之栈与队列十:走迷宫(DFS)

Problem Description

一个由n * m 个格子组成的迷宫,起点是(1, 1), 终点是(n,m),每次可以向上下左右四个方向任意走一步,并且有些格子是不能走动,求从起点到终点经过每个格子至多一次的走法数。

Input

第一行一个整数T 表示有T 组测试数据。(T <= 110)
对于每组测试数据:
第一行两个整数n, m,表示迷宫有n * m 个格子。(1 <= n, m <= 6, (n, m) !=(1, 1) ) 接下来n 行,每行m 个数。其中第i 行第j 个数是0 表示第i 行第j 个格子可以走,否则是1 表示这个格子不能走,输入保证起点和终点都是都是可以走的。
任意两组测试数据间用一个空行分开。

Output

对于每组测试数据,输出一个整数R,表示有R 种走法。

Example Input

3
2 2
0 1
0 0
2 2
0 1
1 0
2 3
0 0 0
0 0 0

Example Output

1
0
4

题意:
找出从(1,1)到(n,m)的路径条数。
分析:
从四个方向依次查找,当找到(n,m)时,记录走的方法数。

用这个方法也可以找到最短路径步数,只需改动 如下:

void dfs(int x,int y,int step)
{
    ....
    if(x == n&&y == m)  //判断是否到达出口位置
    {
        if(step < min)
            min = step;
        return ;    
    }
    ....
}

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n,m;
int step = 0;
int book[1000][1000],e[1000][1000];
void dfs(int x,int y)
{
    int next[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};  //四个方向
    int tx,ty;
    if(x == n&&y == m)  //判断是否到达出口位置
    {
         step ++;   //找到一次记录一次
         return ;    
    }

    for(int i=0;i<=3;i++)
    {
        //下一个点的坐标
        tx = x + next[i][0];
        ty = y + next[i][1];
        //判断是否越界
        if(tx < 1 || tx > n || ty <1 || ty > m)
            continue;
            //判断该点是否能走或者已经在路上
        if(e[tx][ty] == 0 && book[tx][ty] == 0)
        {
            book[tx][ty] = 1;  //标记这个点已被走过
            dfs(tx,ty);   //开始尝试下一个点
            book[tx][ty] = 0;  //当尝试结束时取消标记
        }
    }
    return ;
}
int main()
{
    int T;
    int i,j;
    scanf("%d",&T);
    while(T--)
    {
        step = 0;
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                scanf("%d",&e[i][j]);
            }
        }
        book[1][1] = 1;
        dfs(1,1);
        printf("%d\n",step);
    }
    return 0;
}

转载:https://blog.csdn.net/chrishuimin/article/details/78170951

发布了65 篇原创文章 · 获赞 2 · 访问量 847

猜你喜欢

转载自blog.csdn.net/weixin_43797452/article/details/104524274
今日推荐