sdut 走迷宫
走迷宮
Time Limit: 1000MS Memory limit: 65536K
題目描述
一個由n * m 個格子組成的迷宮,起點是(1, 1), 終點是(n, m),每次可以向上下左右四個方向任意走一步,并且有些格子是不能走動,求從起點到終點經(jīng)過每個格子至多一次的走法數(shù)。
輸入
第一行一個整數(shù)T 表示有T 組測試數(shù)據(jù)。(T <= 110)對于每組測試數(shù)據(jù):
第一行兩個整數(shù)n, m,表示迷宮有n * m 個格子。(1 <= n, m <= 6, (n, m) !=(1, 1) ) 接下來n 行,每行m 個數(shù)。其中第i 行第j 個數(shù)是0 表示第i 行第j 個格子可以走,否則是1 表示這個格子不能走,輸入保證起點和終點都是都是可以走的。
任意兩組測試數(shù)據(jù)間用一個空行分開。
輸出
對于每組測試數(shù)據(jù),輸出一個整數(shù)R,表示有R 種走法。示例輸入
32 20 10 02 20 11 02 30 0 00 0 0示例輸出
104java代碼,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;}}}} }總結(jié)
- 上一篇: java基础回顾之第一章节思维导图
- 下一篇: 互斥锁和条件变量