走迷宫
Time Limit: 1000MS Memory limit: 65536K
题目描述
一个由n * m 个格子组成的迷宫,起点是(1, 1), 终点是(n, m),每次可以向上下左右四个方向任意走一步,并且有些格子是不能走动,求从起点到终点经过每个格子至多一次的走法数。
输入
第一行一个整数T 表示有T 组测试数据。(T <= 110)
对于每组测试数据:
第一行两个整数n, m,表示迷宫有n * m 个格子。(1 <= n, m <= 6, (n, m) !=(1, 1) ) 接下来n 行,每行m 个数。其中第i 行第j 个数是0 表示第i 行第j 个格子可以走,否则是1 表示这个格子不能走,输入保证起点和终点都是都是可以走的。
任意两组测试数据间用一个空行分开。
输出
对于每组测试数据,输出一个整数R,表示有R 种走法。
示例输入
3
2 2
0 1
0 0
2 2
0 1
1 0
2 3
0 0 0
0 0 0
示例输出
1
0
4
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;int s[10][10],n,m,num=0;
int ma[10][10]= {0}; ///0表示没来过这个坐标
int dx[]= {0,0,1,-1};
int dy[]= {-1,1,0,0}; ///上下左右四个位置
void dfs(int x,int y)
{if (x==n&&y==m){num++; ///num为不同的路return;}int i;ma[x][y]=1;for(i=0; i<=3; i++) ///遍历四个位置{if (x+dx[i]>=1 && x+dx[i]<=n && y+dy[i]>=1 &&y+dy[i]<=m && !ma[x+dx[i]][y+dy[i]] && !s[x+dx[i]][y+dy[i]]){ma[x+dx[i]][y+dy[i]]=1; ///记录搜索到状态dfs(x+dx[i],y+dy[i]); ///递归调用ma[x+dx[i]][y+dy[i]]=0; ///将状态调回 因为他可能在下次搜索中用到}}
}int main()
{int t,j,i;scanf("%d",&t);while (t--){num=0;memset(ma,0,sizeof(ma)); ///不要忘记map清零scanf("%d%d",&n,&m);for (i=1; i<=n; i++){for(j=1; j<=m; j++){scanf("%d",&s[i][j]);}}dfs(1,1); ///从1,1开始遍历printf("%d\n",num);}return 0;
}
java代码,2018/03/26重做
public class Main {private static int[][] go = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; // 上下左右public static int m = 0, n = 0, s = 0;private static int[][] vis = new int[10][10];public static void main(String[] args) {int N;Scanner sc = new Scanner(System.in);N = sc.nextInt();for (int i = 0; i < N; i++) {init();m = sc.nextInt();n = sc.nextInt();int[][] a = new int[m][n];for (int i1 = 0; i1 < m; i1++) {for (int j = 0; j < n; j++) {a[i1][j] = sc.nextInt();}}dfs(a, 0, 0);System.out.println(s);s = 0;}}private static void init() {for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {vis[i][j] = 0;}}}private static void dfs(int[][] a, int x, int y) {if (x == m - 1 && y == n - 1) {s++;return;} else { for (int i = 0; i < 4; i++) {int xx = x + go[i][0];int yy = y + go[i][1];if (xx >= 0 && xx < m && yy >= 0 && yy < n && vis[xx][yy] ==0 && a[xx][yy]==0) { x = xx;y = yy;System.out.println("x:"+x+"--"+"y:"+y);vis[x][y] = 1;dfs(a, x, y);System.out.println("yes I do "+x+'-'+y);vis[x][y] = 0;}}}}
}