Leetcode 63. Unique Paths II Java

Source: Internet
Author: User

Topic:

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.

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 .

Note: m and N would be is at most 100.

Test Instructions: given a two-dimensional lattice, where the value of 1 points represents the obstacle point, it is required to find out how many ways to go from the top-left point to the bottom-right point. Using dynamic planning, for one of the points obstaclegrid[i][j] (1<i<m,i<j<n), the way to that point is D (Obstaclegrid[i][j]) =d (Obstaclegrid[i-1][j]) +d (Obstaclegrid[i][j-1]), for the first and first columns, if there is a barrier point in front of the point, then there are 0 methods to that point, and vice versa is 1. Iterating through an array solves the problem.

Code:

public class Solution {public int uniquepathswithobstacles (int[][] obstaclegrid) {int m=obstaclegrid.length;//line int n=0 ;//column if (m!=0) n=obstaclegrid[0].length;int[][] a=new int[m][n];//user record start point to current Point walk for (int. i=0;i<m;i++) {for (int <n;j++) {if (obstaclegrid[i][j]==1)//If a point barrier point, then only 0 methods a[i][j]=0;else{if to that point (i==0| | j==0) {//If it is the first column or the first row, if there is a barrier point in front of that point, then pity Dorado is also not reachable by the Boolean obstracle=false;if (i==0) {for (int k=0;k<j;k++) {if ( obstaclegrid[i][k]==1) obstracle=true;}} else if (j==0) {for (int k=0;k<i;k++) {if (obstaclegrid[k][j]==1) obstracle=true;}} if (obstracle) A[i][j]=0;else a[i][j]=1;} else a[i][j]=a[i-1][j]+a[i][j-1];}}} return a[m-1][n-1];}}

  

Leetcode 63. Unique Paths II Java

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.