[Dynamic programming] nxm matrix, start point (1,1), end point (n, m). Each time you can go down or to the right, each time the number of steps needs to be an odd number, find the number of paths.

topic

Now there is an n×m matrix, Xiaohong is at (1,1), and the end point is (n,m). (1,1) is upper left, (n, m) is lower right. Every time you can go down or to the right, the number of steps needs to be an odd number.
Xiaohong wants to know how many plans she has to reach the end, can you help her count it?
insert image description here
Test example:

1
2 4
output result: 6
2
5 4
3 6
output result: 66
54

insert image description here
insert image description here
insert image description here

ps

By the way, this topic is very similar to Leetcode, but not the same
https://leetcode.cn/problems/unique-paths/

code:

This code is written by myself and has not been submitted. I am not sure about it.

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
#define M 1000000007
int uniquePaths(int m, int n) {
    
    
        vector<vector<int>> f(m, vector<int>(n));
        f[0][0] = 1;
        for (int i = 0; i < m; ++i) {
    
    
            for (int j = 0; j < n; ++j) {
    
    
                // f[i][j] = f[i - 1][j] + f[i][j - 1];
                if(i == 0 && j == 0){
    
    
                    continue;
                }
                for(int k= j-1; k >= 0; k -= 2){
    
    
                    f[i][j]= (f[i][j] + f[i][k])% M;
                }
                for(int k= i-1 ;k >= 0;k -= 2){
    
    
                    f[i][j]= (f[i][j] + f[k][j])% M;
                }
            } 
        }
        return f[m - 1][n - 1];
}
int main(){
    
     
    int T;
    cin>>T;
    while(T--){
    
    
        int m,n;
        cin>>m>>n;
        cout<< uniquePaths(m,n)<<endl;
    }
}

Guess you like

Origin blog.csdn.net/holly_Z_P_F/article/details/126962194