# 115.Unique Paths II

## 1.Description(Easy)

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as`1`and`0`respectively in the grid.

### Notice

m and n will be at most 100.

**Example**

For example,\
There is one obstacle in the middle of a 3x3 grid as illustrated below.

```
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
```

The total number of unique paths is`2`.

## 2.Code

初始化第0行0列都只有一种走法

初始化的时候注意，若此处是1，则0行/0列后面所有的

```
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid==null || obstacleGrid[0].length==0){
            return 0;
        }
        if(obstacleGrid[0]==null || obstacleGrid[0].length==0){
            return 0;
        }

        int n=obstacleGrid.length;
        int m=obstacleGrid[0].length;

        //state:
        int[][] f=new int[n][m];

        //Initialization:
        /*if(obstacleGrid[0][0]!=1){
            f[0][0]=1;
        }
        else{
            return -1;
        }*/

        for(int i=0;i<m;i++){
            if(obstacleGrid[0][i]!=1){
                f[0][i]=1;
            }
            else{
                break;
            }
        }
        for(int i=0;i<n;i++){
            if(obstacleGrid[i][0]!=1){
                f[i][0]=1;
            }
            else{
                break;
                }
        }


        //function:
        for(int i=1;i<n;i++){
            for(int j=1;j<m;j++){
                if(obstacleGrid[i][j]!=1){
                    f[i][j]=f[i-1][j]+f[i][j-1];
                }
                else{
                    f[i][j]=0;
                }
            }
        }

        //answer:
        return f[n-1][m-1];
    }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/9.dynamic-programming/115unique-paths-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
