1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| int ret = 0;
class Solution { public: void dfs(int x, int y, vector<vector<int>>& grid, int cur_zeros, int zeros) { if (grid[x][y] == 2) { if (cur_zeros == zeros) { ret ++; } return; } if (x - 1 >= 0 && grid[x - 1][y] != -1) { if (!grid[x - 1][y]) { grid[x - 1][y]--; dfs(x - 1, y, grid, cur_zeros + 1, zeros); grid[x - 1][y]++; } else dfs(x - 1, y, grid, cur_zeros, zeros); } if (x + 1 < grid.size() && grid[x + 1][y] != -1) { if (!grid[x + 1][y]) { grid[x + 1][y]--; dfs(x + 1, y, grid, cur_zeros + 1, zeros); grid[x + 1][y]++; } else dfs(x + 1, y, grid, cur_zeros, zeros); } if (y - 1 >= 0 && grid[x][y - 1] != -1) { if (!grid[x][y - 1]) { grid[x][y - 1]--; dfs(x, y - 1, grid, cur_zeros + 1, zeros); grid[x][y - 1]++; } else dfs(x, y - 1, grid, cur_zeros, zeros); } if (y + 1 < grid[0].size() && grid[x][y + 1] != -1) { if (!grid[x][y + 1]) { grid[x][y + 1]--; dfs(x, y + 1, grid, cur_zeros + 1, zeros); grid[x][y + 1]++; } else dfs(x, y + 1, grid, cur_zeros, zeros); } } int uniquePathsIII(vector<vector<int>>& grid) { ret = 0; int zeros = 0; int startx, starty, endx, endy; int m = grid.size(); int n = grid[0].size(); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { if (grid[i][j] == 0) zeros++; if (grid[i][j] == 1) { startx = i; starty = j; } if (grid[i][j] == 2) { endx = i; endy = j; } } grid[startx][starty] = -1; dfs(startx, starty, grid, 0, zeros); return ret; } };
|