走迷宫
Time Limit: 1000MS Memory Limit: 65536KB
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
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
bool Map[105][105];
bool vis[105][105];
int n, m, cnt;
void DFS(int x, int y)
{
if(x == n-1 && y == m-1)
{
cnt++;
return ;
}
if(x < 0 || y < 0 || x >= n || y >= m)
return ;
if(Map[x][y] == 0 && !vis[x][y])
{
vis[x][y] = 1;
DFS(x+1, y);
DFS(x-1, y);
DFS(x, y+1);
DFS(x, y-1);
vis[x][y] = 0;
}
}
int main()
{
int t;
while(cin >> t)
{
while(t--)
{
memset(Map,0,sizeof(Map));
memset(vis,0,sizeof(vis));
cin >> n >> m;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
cin >> Map[i][j];
}
cnt = 0;
DFS(0,0);
cout << cnt << endl;
}
}
return 0;
}