一个由n * m 个格子组成的迷宫,起点是(1, 1), 终点是(n, m),每次可以向上下左右四个方向任意走一步,并且有些格子是不能走动,求从起点到终点经过每个格子至多一次的走法数。
对于每组测试数据:
第一行两个整数n, m,表示迷宫有n * m 个格子。(1 <= n, m <= 6, (n, m) !=(1, 1) ) 接下来n 行,每行m 个数。其中第i 行第j 个数是0 表示第i 行第j 个格子可以走,否则是1 表示这个格子不能走,输入保证起点和终点都是都是可以走的。
任意两组测试数据间用一个空行分开。
32 20 10 02 20 11 02 30 0 00 0 0Example Output
104#include<stdio.h>#include<string.h>#include<stdlib.h>#define max 7int book[max][max];int df[max][max];int count,n,m;void dfs(int x,int y){ int i,tx,ty; if(x==n&&y==m) { count++; return ; } int next[4][2]={{-1,0},{0,1},{1,0},{0,-1}}; for(i=0;i<4;i++) { tx=x+next[i][0]; ty=y+next[i][1]; if(tx<1||tx>n||ty<1||ty>m) continue; if(df[tx][ty]!=1&&book[tx][ty]==0) { book[tx][ty]=1; dfs(tx,ty); book[tx][ty]=0; } }}int main(){ int t,i,j; scanf("%d",&t); while(t--) { count=0; scanf("%d%d",&n,&m); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%d",&df[i][j]); } } book[1][1]=1; dfs(1,1); printf("%d/n",count); } return 0;}
新闻热点
疑难解答