题目地址:
https://www.lintcode.com/problem/1829/description
给定一个 n n n行 m m m列的二维 0 − 1 0-1 0−1矩阵,可以从第一行任意位置出发,每次上下左右走一步,走到最后一行任意位置为止。问走到最后一行的所有最短路的条数。
其实就是在BFS树上按拓扑序做递推求方案数。想象开一个虚拟源点,向第一行的每个 0 0 0都连一条边,这里要开两个二维数组 D D D和 C C C, D [ i ] [ j ] D[i][j] D[i][j]代表从第一行走到 ( i , j ) (i,j) (i,j)这个位置的最短路的长度, C [ i ] [ j ] C[i][j] C[i][j]表示从第一行走到 ( i , j ) (i,j) (i,j)这个位置的最短路条数,接着做BFS遍历即可。实际代码里不需要真的把虚拟源点建出来,可以直接将第一行的 0 0 0的位置入队。代码如下:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
/**
* @param n: the row of the map
* @param m: the column of the map
* @param A: the map
* @return: the number of shortest path
*/
public int theNumberofShortestPath(int n, int m, int[][] A) {
// write your code here
Queue<int[]> queue = new LinkedList<>();
int[][] dist = new int[n][m], cnt = new int[n][m];
for (int[] row : dist) {
Arrays.fill(row, -1);
}
for (int i = 0; i < m; i++) {
if (A[0][i] == 0) {
queue.offer(new int[]{0, i});
dist[0][i] = 0;
cnt[0][i] = 1;
}
}
int step = 0;
// flag标记的是是否已经走到了最后一行
boolean flag = false;
int[] d = {1, 0, -1, 0, 1};
while (!queue.isEmpty()) {
step++;
for (int i = queue.size(); i > 0; i--) {
int[] cur = queue.poll();
for (int j = 0; j < 4; j++) {
int x = cur[0], y = cur[1];
int nextX = x + d[j], nextY = y + d[j + 1];
if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m && A[nextX][nextY] == 0) {
// 如果是第一次走到,那么就得到了最短路长度;否则如果发现了另一条最短路,则累加方案数
if (dist[nextX][nextY] == -1) {
dist[nextX][nextY] = step;
cnt[nextX][nextY] = cnt[x][y];
queue.offer(new int[]{nextX, nextY});
// 走到了最后一行就标记一下,本层BFS结束后直接退出while循环
if (nextX == n - 1) {
flag = true;
}
} else if (dist[nextX][nextY] == step) {
cnt[nextX][nextY] += cnt[x][y];
}
}
}
}
if (flag) {
break;
}
}
int res = 0;
for (int x : cnt[n - 1]) {
res += x;
}
return res;
}
}
时空复杂度 O ( n m ) O(nm) O(nm)。