77
77
class Solution {
78
78
int zeros = 0 ;
79
79
private int callme (int x , int y , int [][] grid ){
80
- if (x <0 || y <0 || x >=grid .length || y >=grid [0 ].length )
80
+ if (x <0 || y <0 || x >=grid .length || y >=grid [0 ].length || grid [ x ][ y ] == - 1 || grid [ x ][ y ] == 3 )
81
81
return 0 ;
82
- if (grid [x ][y ] == -1 || grid [x ][y ] == 3 )
83
- return 0 ;
84
- if (grid [x ][y ] == 2 ){
85
- if (zeros == 0 )
86
- return 1 ;
87
- else
88
- return 0 ;
89
- }
90
82
91
- zeros --;
92
- grid [x ][y ] = 3 ;
83
+ if (grid [x ][y ] == 2 )
84
+ return zeros == 0 ? 1 : 0 ;
85
+
93
86
int ret = 0 ;
94
87
88
+ grid [x ][y ] = 3 ;
89
+ zeros --;
90
+
95
91
//left
96
92
ret += callme (x , y -1 , grid );
97
93
//right
@@ -103,23 +99,24 @@ private int callme(int x, int y, int[][] grid){
103
99
104
100
zeros ++;
105
101
grid [x ][y ] = 0 ;
102
+
106
103
return ret ;
107
104
}
108
105
109
106
public int uniquePathsIII (int [][] grid ) {
110
107
108
+ int x = 0 , y = 0 ;
111
109
for (int i =0 ; i <grid .length ; i ++)
112
110
for (int j =0 ; j <grid [0 ].length ; j ++)
113
111
if (grid [i ][j ] == 0 )
114
112
zeros ++;
115
- for (int i =0 ; i <grid .length ; i ++)
116
- for (int j =0 ; j <grid [0 ].length ; j ++)
117
- if (grid [i ][j ] == 1 ){
118
- grid [i ][j ] = -1 ;
119
- return callme (i +1 , j , grid )+callme (i -1 , j , grid )+callme (i , j -1 , grid )+callme (i , j +1 , grid );
113
+ else if (grid [i ][j ] == 1 ){
114
+ x = i ;
115
+ y = j ;
120
116
}
121
117
122
- return 0 ;
118
+ grid [x ][y ] = -1 ;
119
+ return callme (x +1 , y , grid )+callme (x -1 , y , grid )+callme (x , y -1 , grid )+callme (x , y +1 , grid );
123
120
}
124
121
}
125
122
// @lc code=end
0 commit comments