unique-paths-ii.dart (1610B)
1 //Given a matrix return the total number of possible ways to traverse the grid from top left to 2 //bottom right. The challenge in this one lies in the fact that there are certain 1's on the board 3 //that are obstacles and thus can not be traversed. 4 //To solve this I took each right and down path for each tile to find out how many times each choice could 5 //reach the end. To optimize this I saved that value to each memoized tile that way if a tile had been 6 //traversed already the number of paths would not need to be recomputed. 7 //Time: 298ms Beats: 100% 8 //Memory: 145.7MB Beats: 100% 9 10 class Solution { 11 int uniquePathsWithObstacles(List<List<int>> obstacleGrid) { 12 Map<String,int> memo = {}; 13 return uniquePaths(obstacleGrid, [0,0], memo); 14 } 15 int uniquePaths(List<List<int>> grid , List<int> current_position, Map<String,int> memo){ 16 if(current_position[0] >= grid.length || current_position[1] >= grid[0].length || grid[current_position[0]][current_position[1]] == 1){ 17 return 0; 18 } 19 if(current_position[0] == grid.length - 1 && current_position[1] == grid[0].length - 1){ 20 return 1; 21 } 22 String current = current_position[0].toString() + ' ' + current_position[1].toString(); 23 24 if(memo.containsKey(current)){ 25 return(memo[current] ?? 0); 26 } 27 int return_paths = 0; 28 return_paths += uniquePaths(grid, [current_position[0] + 1 , current_position[1]], memo); 29 return_paths += uniquePaths(grid, [current_position[0] , current_position[1] + 1], memo); 30 memo[current] = return_paths; 31 return return_paths; 32 } 33 }