|
| 1 | +class Solution { |
| 2 | + |
| 3 | + /** |
| 4 | + * @param Integer[][] $obstacleGrid |
| 5 | + * @return Integer |
| 6 | + */ |
| 7 | + function uniquePathsWithObstacles($obstacleGrid) { |
| 8 | + $rows = count($obstacleGrid); |
| 9 | + $cols = count($obstacleGrid[0]); |
| 10 | + $temp=array_fill(0, $rows, array_fill(0, $cols, 0)); |
| 11 | + // If starting point is Obstacle, no way to reach end. |
| 12 | + if($obstacleGrid[0][0]==1) |
| 13 | + return 0; |
| 14 | + // Starting point. |
| 15 | + $temp[0][0]=1; |
| 16 | + for($row=0;$row<$rows;$row++){ |
| 17 | + for ($col=0;$col<$cols;$col++){ |
| 18 | + if($col==0 && $row==0) |
| 19 | + continue; |
| 20 | + if($obstacleGrid[$row][$col]!=1){ |
| 21 | + $upVal=($row-1)<0?0: $temp[$row-1][$col]; |
| 22 | + $leftVal=($col-1)<0?0: $temp[$row][$col-1]; |
| 23 | + // Number of ways to reach current cell. |
| 24 | + // No. of ways to reach uppper cell + No.of ways to reach left cell. |
| 25 | + $temp[$row][$col]=$upVal+$leftVal; |
| 26 | + } |
| 27 | + |
| 28 | + } |
| 29 | + } |
| 30 | + return $temp[$rows-1][$cols-1]; |
| 31 | + } |
| 32 | +} |
0 commit comments