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:
Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths:
/* @param: int[][] grid @return: int Algorithm: 常规DFS+backtracking */ int res, todo = 1, sx, sy, ex, ey, row, col; publicintuniquePathsIII(int[][] grid){ row = grid.length; col = grid[0].length; if (row == 0 || col == 0) { return0; } res = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 0) { todo++; }elseif (grid[i][j] == 1) { sx = i; sy = j; }elseif (grid[i][j] == 2) { ex = i; ey = j; } } } dfs(sx, sy, grid); return res; }
publicvoiddfs(int x, int y, int[][] grid){ if (x < 0 || y < 0 || x >= row || y >= col || grid[x][y] < 0) { return; } if (x == ex && y == ey ) { if (todo == 0){ res++; } return; } todo--; grid[x][y] = -2; dfs(x+1,y,grid); dfs(x-1,y,grid); dfs(x,y+1,grid); dfs(x,y-1,grid); todo++; grid[x][y] = 0; }