[Leetcode] (python): 063-unique path II

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/unique-paths-ii/

Follow up for "Unique Paths":

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

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

Test instructions Analysis

Input:a matrix as List[list[int]]

Output:the Number of Path

Conditions: From the upper left corner to the lower left, notice that obstacles cannot be passed.

Topic ideas

The previous question is a mathematical method of direct solution, this topic with dynamic planning bar, because each step will be based on the last lattice or the left one lattice, the dynamic equation is dp[i][j] = Dp[i][j-1] + dp[i-1][j]

Note that if an obstacle is encountered during initialization, the subsequent position cannot be initialized to 0.

AC Code (PYTHON)

1 classsolution (object):2     defuniquepathswithobstacles (Self, obstaclegrid):3         """4 : Type Obstaclegrid:list[list[int]]5 : Rtype:int6         """7m =Len (Obstaclegrid)8n =Len (obstaclegrid[0])9DP = [[0 forIinchRange (n)] forJinchrange (m)]Ten          forIinchrange (n): One             ifObstaclegrid[0][i] = = 1: A                  Break -             Else: -Dp[0][i] = 1 the          -          forIinchRange (m): -             ifObstaclegrid[i][0] = = 1: -                  Break +             Else: -Dp[i][0] = 1 +          A          forIinchRange (1, m): at              forJinchRange (1, N): -                 ifOBSTACLEGRID[I][J] = =0: -DP[I][J] = Dp[i-1][j] + dp[i][j-1] -          -         returnDP[M-1][N-1]

[Leetcode] (python): 063-unique path II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.