python實現從二維矩陣左上角到右下角的出路數尋找
阿新 • • 發佈:2018-12-24
問題:
給定一個二微矩陣,從左上角出發到右下角,每一次只能往下和往右走,求一共有多少種走法
具體實現如下:
#!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水寒城 功能:在二維矩陣中向下和向右走,實現從左上角走到右下角 ''' def count_dp(x,y): ''' 動態規劃 ''' matrix=[[1]*y for i in range(x)] for i in range(1,x): for j in range(1,y): matrix[i][j]=matrix[i-1][j]+matrix[i][j-1] return matrix[x-1][y-1] if __name__ == "__main__": num_list=[[3,4],[5,4],[7,7],[15,15]] for one_position in num_list: x,y=one_position print '{0}row {1}col matrix all walk ways are:{2}'.format(x,y,count_dp(x,y))
結果如下:
3row 4col matrix all walk ways are:10
5row 4col matrix all walk ways are:35
7row 7col matrix all walk ways are:924
15row 15col matrix all walk ways are:40116600
[Finished in 0.2s]