How many routes does the grid move from the lower left corner to the upper right corner (dynamic planning)

A problem encountered during the interview, the ants crawled from the corner of the grid (m, n) to the opposite corner (can not crawl back), checked some things, wrote some of their own understanding, and hoped the great god to give pointers.


Climb from one corner of the grid to the opposite corner.

Understanding part:
Convert it to how many movement methods there are from (m, n) coordinates to (0,0) coordinates. (Only move down, move left)
。 。 。 。 。 。
。 。 。 。 。 。
1 3 6 10 。 。
1 2 3 4 。 。
0 1 1 1 。 。

As shown in the above figure, the route from (m, n) to (0,0) is divided into a series of subdivisions,
(I, j) is the position of the point. The starting position is (m, n).
(M, n) = (m, n-1) + (m-1, n); There are two ways of walking.
(M, n-1) = (m, n-2) + (m-1, n-1); that is, (m, n-1) point, there are two ways to follow, the same reason (m-1, n) = (m-1, n-1) + (m-2, n);
。。。。
When i = 0 or j = 0 in (i, j), then you can only move right or up, that is, there is only one way to move.
That is, m = 0, or n = 0, there is only one way to go, return 1;

code show as below:

public class GridCrawl {

public static int crawl(int m,int n){
if (m> 0 && n> 0) // This coordinate can be moved down or left
{
return crawl(m, n - 1) + crawl(m - 1, n);
}
else if ((m == 0) && (n> 0)) // Can only move down
{
return crawl(m,n-1);
}
else if ((n == 0) && (m> 0)) // Can only move left
{
return crawl(m-1,n);
}
else if ((m == 1 && n == 0) || (m == 0 && n == 1))
{
return 1;
}
else
return 0;
}
}

简化写法

public static int crawl(int m,int n){
if(m == 0 && n == 0)
return 0;
if(m == 0 || n == 0)
return 1;
return crawl(m-1,n)+crawl(m,n-1);
}



发布了26 篇原创文章 · 获赞 0 · 访问量 9938

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/78660251