SDUT_2449_數據結構實驗之棧與隊列十:走迷宮

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章