赞
踩
讲解链接:代码随想录-62.不同路径
- public int uniquePaths(int m, int n) {
- int[][] paths = new int[m][n];
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- int sum = 1;
- if (i == 0 && j == 0) {
- sum = 1;
- } else if (i == 0 && j > 0) {
- sum = paths[i][j - 1];
- } else if (i > 0 && j == 0) {
- sum = paths[i - 1][j];
- } else if (i > 0 && j > 0) {
- sum = paths[i - 1][j] + paths[i][j - 1];
- }
-
- paths[i][j] = sum;
- }
- }
- return paths[m - 1][n - 1];
- }
讲解链接:代码随想录-63.不同路径 II
在当前节点的时候,需要判断上一节点是否有障碍物,有的话初始化就是 0。
需要注意开头、终点或中间出现死路的情况。
- public int uniquePathsWithObstacles(int[][] obstacleGrid) {
- int h = obstacleGrid.length, w = obstacleGrid[0].length;
- // 如果在起点或终点出现障碍物,直接返回0
- if (obstacleGrid[0][0] > 0 || obstacleGrid[h - 1][w - 1] > 0) {
- return 0;
- }
-
- int[][] db = new int[h][w];
- for (int i = 0; i < h; i++) {
- for (int j = 0; j < w; j++) {
- // 只有当 0,0 的时候,pathNum默认为1
- int pathNum = 1;
- if (i > 0 && j == 0) {
- pathNum = obstacleGrid[i - 1][j] > 0 ? 0 : db[i - 1][j];
- } else if (i == 0 && j > 0) {
- pathNum = obstacleGrid[i][j - 1] > 0 ? 0 : db[i][j - 1];
- } else if (i > 0 && j > 0) {
- int top = obstacleGrid[i - 1][j] > 0 ? 0 : db[i - 1][j];
- int left = obstacleGrid[i][j - 1] > 0 ? 0 : db[i][j - 1];
- pathNum = top + left;
- }
- db[i][j] = pathNum;
- }
- }
- return db[h - 1][w - 1];
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。