# 23. 不同路径

起点(0,0)，每次只能右走或者下走，能有多少条路径到目的地

python

```python
X = []
x = []


def next(m, n, i, j):
  # mxn网格，从(i,j)到(m-1,n-1)方向走
    if i > m - 1 or j > n - 1:# 如果超出去了舍去返回，停止递归
        return
    if i == m - 1 and j == n - 1:# 如果刚好右下角，则X记录路径x
        X.append(x[:])
    else: # 否则，继续往下走
        # x记录下一个点(i,j+1)
        x.append((i, j + 1))
        next(m, n, i, j + 1)
        # 走完尝试(i,j+1)后弹出，找新的尝试
        x.pop()

        x.append((i + 1, j))
        next(m, n, i + 1, j)
        x.pop()


if __name__ == '__main__':
  # 在4x3网格，(0,0)点，到(3,2)点，（左上到右下）
    m = 4
    n = 3
    next(m, n, 0, 0)
    print(X)

'''
[[(0, 1), (0, 2), (1, 2), (2, 2), (3, 2)], 
[(0, 1), (1, 1), (1, 2), (2, 2), (3, 2)], 
[(0, 1), (1, 1), (2, 1), (2, 2), (3, 2)], 
[(0, 1), (1, 1), (2, 1), (3, 1), (3, 2)], 
[(1, 0), (1, 1), (1, 2), (2, 2), (3, 2)], 
[(1, 0), (1, 1), (2, 1), (2, 2), (3, 2)], 
[(1, 0), (1, 1), (2, 1), (3, 1), (3, 2)], 
[(1, 0), (2, 0), (2, 1), (2, 2), (3, 2)], 
[(1, 0), (2, 0), (2, 1), (3, 1), (3, 2)], 
[(1, 0), (2, 0), (3, 0), (3, 1), (3, 2)]]
'''
```

java

```java
/**
 * 不同路径
 *
 * 一个机器人位于一个 m x n 网格的左上角 （起始点在下图中标记为“Start” ）。
 *
 * 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角（在下图中标记为“Finish”）。
 *
 * 问总共有多少条不同的路径？
 *
 *
 * 例如，上图是一个7 x 3 的网格。有多少可能的路径？
 *
 * 说明：m 和 n 的值均不超过 100。
 *
 * 示例 1:
 *
 * 输入: m = 3, n = 2
 * 输出: 3
 * 解释:
 * 从左上角开始，总共有 3 条路径可以到达右下角。
 * 1. 向右 -> 向右 -> 向下
 * 2. 向右 -> 向下 -> 向右
 * 3. 向下 -> 向右 -> 向右
 *
 * 示例 2:
 *
 * 输入: m = 7, n = 3
 * 输出: 28
 */
public class Solution62 {

    /**
     * 使用动态规划求解.
     *
     * 第一行、第一列设为1，从第二行第二列开始，
     * 该位置的路径数等于左侧的路径数+上侧的路径数，
     * 机器人到达右下角的路径未arr[m-1][n-1]
     *
     * @param m
     * @param n
     * @return
     */
    public int uniquePaths(int m, int n) {
        int[][] arr=new int[m][n];
        for(int i=0;i<m;i++) arr[i][0]=1;
        for(int i=0;i<n;i++) arr[0][i]=1;
        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                arr[i][j]=arr[i-1][j]+arr[i][j-1];
            }
        }
        return arr[m-1][n-1];
    }

    public static void main(String[] args){
        int m=3,n=2;
        int r=new Solution62().uniquePaths(m,n);
        System.out.println(r);
    }
}
```


---

# Agent Instructions: 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://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/shu-ju-jie-gou-lei/23-bu-tong-lu-jin.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.
