题目

On a 2-dimensional grid, there are 4 types of squares:

  • 1 represents the starting square. There is exactly one starting square.
  • 2 represents the ending square. There is exactly one ending square.
  • 0 represents empty squares we can walk over.
  • -1 represents obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

Example 1:

  1. Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
  2. Output: 2
  3. Explanation: We have the following two paths:
  4. 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
  5. 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)

Example 2:

  1. Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
  2. Output: 4
  3. Explanation: We have the following four paths:
  4. 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
  5. 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
  6. 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
  7. 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)

Example 3:

  1. Input: [[0,1],[2,0]]
  2. Output: 0
  3. Explanation:
  4. There is no path that walks over every empty square exactly once.
  5. Note that the starting and ending square can be anywhere in the grid.

Note:

  1. 1 <= grid.length * grid[0].length <= 20

题意

给定一个二维数组,1表示起点,2表示终点,0表示可通行,-1表示不可通行。找到一条从起点到终点的路径,使其能通过所有可通行的点,统计这样的路径的个数。

思路

直接暴力回溯就能AC。


代码实现

Java

  1. class Solution {
  2. private int count;
  3. private int m, n;
  4. private int[] iPlus = { -1, 0, 1, 0 };
  5. private int[] jPlus = { 0, 1, 0, -1 };
  6. public int uniquePathsIII(int[][] grid) {
  7. m = grid.length;
  8. n = grid[0].length;
  9. int x = 0, y = 0;
  10. int left = 0;
  11. for (int i = 0; i < m; i++) {
  12. for (int j = 0; j < n; j++) {
  13. if (grid[i][j] >= 0) {
  14. left++;
  15. }
  16. if (grid[i][j] == 1) {
  17. x = i;
  18. y = j;
  19. }
  20. }
  21. }
  22. dfs(grid, x, y, left, new boolean[m][n]);
  23. return count;
  24. }
  25. private void dfs(int[][] grid, int i, int j, int left, boolean visited[][]) {
  26. if (grid[i][j] == 2 && left == 1) {
  27. count++;
  28. return;
  29. }
  30. visited[i][j] = true;
  31. for (int x = 0; x < 4; x++) {
  32. int nextI = i + iPlus[x];
  33. int nextJ = j + jPlus[x];
  34. if (isValid(grid, nextI, nextJ) && !visited[nextI][nextJ]) {
  35. dfs(grid, nextI, nextJ, left - 1, visited);
  36. }
  37. }
  38. visited[i][j] = false;
  39. }
  40. private boolean isValid(int[][] grid, int i, int j) {
  41. return i >= 0 && i < m && j >= 0 && j < n && grid[i][j] != -1;
  42. }
  43. }