Java simple code O(1) space by modifying input grid


  • 0

    because 1 is used as obstacle, which will be confused with "1 way", we use negative value to represent number of ways.

    public class Solution {
        public int uniquePathsWithObstacles(int[][] obstacleGrid) {
            if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
                return 0;
            }
            int m = obstacleGrid.length;
            int n = obstacleGrid[0].length;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (obstacleGrid[i][j] == 1) {
                        continue;
                    }
                   
                    obstacleGrid[i][j] = (i == 0 || obstacleGrid[i - 1][j] == 1 ? 0 : obstacleGrid[i - 1][j])
                                       + (j == 0 || obstacleGrid[i][j - 1] == 1 ? 0 : obstacleGrid[i][j - 1])
                                       + (i == 0 && j == 0 ? -1 : 0);
                }
            }
            return obstacleGrid[m - 1][n - 1] >= 0 ? 0 : -obstacleGrid[m - 1][n - 1];
        }
    }

  • 0

    Interesting trick, I tried O(1) space by save obstacle remark in the lowest bit and use higher bits to save numPath, but a testcase failed since numPath<<1 goes beyond int range


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.