注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
在做LeetCode的[这道题](https://leetcode.com/problems/unique-paths-iii/),大概就是一个2维格子中存在障碍物,看走完所有格子一共有多少种方法。看了 Discuss 里面[这个解答](https://leetcode.com/problems/un ... Force-Backstracking)之后自己又写了一遍。代码如下:- class Solution {
- int result = 0, empty = 1, sx, sy;
- public int uniquePathsIII(int[][] grid) {
- int n = grid.length, m = grid[0].length;
- for (int i = 0; i < n; i++){
- for (int j = 0; j < m; j++){
- if (grid[i][j] == 0){
- empty++;
- }else if (grid[i][j] == 1){
- sx = i;
- sy = j;
- }
- }
- }
- dfs(grid, sx, sy);
- return result;
- }
-
- public void dfs(int[][] grid, int x0, int y0){
- if (!check(grid, x0, y0)) return;
- if (grid[x0][y0] == 2 && empty == 0){
- result++;
- return;
- }
- grid[x0][y0] = -1;
- empty--;
-
- dfs(grid, x0 + 1, y0);
- dfs(grid, x0 - 1, y0);
- dfs(grid, x0, y0 + 1);
- dfs(grid, x0, y0 - 1);
-
- grid[x0][y0] = 0;
- empty++;
- }
-
- public boolean check(int[][] grid, int x, int y){
- int n = grid.length, m = grid[0].length;
- return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] >= 0;
- }
- }
复制代码
结果就是无论如何返回的都是初始设定的 result 值,没有改变。我想我写的代码的逻辑是对的,但因为 Java 还正在学习中所以不知道是不是 Java 的语言方面出了什么问题。希望大家可以看看什么地方错了。谢谢!
[/i][/i] |