unique-paths-iii.dart (2716B)
1 //Given a grid return all possible traversals of the grid such that you never 2 //go to spots with obstacles (-1) and you never miss a single square. Also, you start 3 //from 1 and end at 2 which can be any position on the board. 4 5 //I solved this using backtracking as there is not a good way to memoize this problem. Starting out 6 //I first found where the starting point was located which is the spot that equals 1. From there I called 7 //my function that checks all paths to find all paths to the endpoint (2) that visits every square. This 8 //function works using DFS where each iteration creates a new grid with the last position visited marked 9 //as -1 so that you never go back and you can always know if you have visited all points. From here you keep moving 10 //until you either reach out of bounds, an obstacle (or a prevously visited spot), or the end point. If you reach the end 11 //point it then checks the entire matrix to see if there are any spots that have been unvisited that should have been visited 12 //if there are not then add 1 to the answer. 13 14 //Time: 294ms Beats: 100% 15 //Memory: 150MB Beats: 100% 16 17 class Solution { 18 int uniquePathsIII(List<List<int>> grid) { 19 for(int i = 0 ; i < grid.length ; ++i){ 20 for(int x = 0 ; x < grid[i].length ; ++x){ 21 if(grid[i][x] == 1){ 22 return(traverse(grid, [i,x])); 23 } 24 } 25 } 26 return 0; 27 } 28 int traverse(List<List<int>> grid , List<int> current_position){ 29 if(current_position[0] < 0 || current_position[0] >= grid.length){ 30 return 0; 31 } 32 if(current_position[1] < 0 || current_position[1] >= grid[current_position[0]].length ){ 33 return 0; 34 } 35 if(grid[current_position[0]][current_position[1]] == -1){ 36 return 0; 37 } 38 List<List<int>> my_grid = []; 39 for(int i = 0 ; i < grid.length ; ++i){ 40 my_grid.add(List.from(grid[i])); 41 } 42 my_grid[current_position[0]][current_position[1]] = -1; 43 44 if(grid[current_position[0]][current_position[1]] == 2){ 45 for(int i = 0 ; i < grid.length ; ++i){ 46 for(int x = 0 ; x < grid[i].length ; ++x){ 47 if(my_grid[i][x] == 0){ 48 return 0; 49 } 50 } 51 } 52 return 1; 53 } 54 55 int return_int = 0; 56 return_int += traverse(my_grid, [current_position[0] , current_position[1] - 1]); 57 return_int += traverse(my_grid, [current_position[0] , current_position[1] + 1]); 58 return_int += traverse(my_grid, [current_position[0] - 1, current_position[1]]); 59 return_int += traverse(my_grid, [current_position[0] + 1 , current_position[1]]); 60 return return_int; 61 } 62 }