题解 | #挤奶路径2#
挤奶路径2
https://www.nowcoder.com/practice/4d315070d57b40bea7a8586793d656bc
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cows int整型二维数组 * @return int整型 */ public int uniquePathsWithCows (int[][] cows) { // write code here int m = cows.length, n = cows[0].length; // 1.找出必经点 int x = 0, y = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (cows[i][j] == 2) { x = i; y = j; } } } // 2.从起点到必经点 int[][] dp1 = new int[x + 2][y + 2]; dp1[1][1] = 1; for (int i = 1; i < x + 2; i++) { for (int j = 1; j < y + 2; j++) { if (cows[i - 1][j - 1] != 1 && i * j != 1) { dp1[i][j] = dp1[i - 1][j] + dp1[i][j - 1]; } } } // 3.从必经点到终点 int[][] dp2 = new int[m - x + 1][n - y + 1]; dp2[1][1] = 1; for (int i = 1; i < m - x + 1; i++) { for (int j = 1; j < n - y + 1; j++) { if (cows[i + x - 1][j + y - 1] != 1 && i * j != 1) { dp2[i][j] = dp2[i - 1][j] + dp2[i][j - 1]; } } } System.out.print(dp2[m - x][n - y]); return dp1[x + 1][y + 1] * dp2[m - x][n - y]; } }