Algorithm: Dynamic programming finds the total number of possible paths to a certain coordinate in the 2D matrix

dp basic problem: find the total number of possible paths to a certain coordinate in the 2D matrix

Problem Description:

Given a two-dimensional array, the solution starts from (0, 0) and the number of possible paths to (x, y). In the matrix, you can only move down or to the right one unit at a time.

problem analysis:

The idea of ​​solving this problem is similar to the previous blog post .

Because the restricted conditions can only move to the right or down, the last step to reach a certain coordinate is down or right. Both of these steps are ways to reach this coordinate. Therefore, if numWays[i][j] is used to represent the total number of paths to the coordinates (i, j), the formula can be obtained:

numWays(i, j) = numWays(i - 1, j) + numWays[i][j - 1]

Now continue to decompose the problem, starting from the coordinates (0, 0), you can notice that there are two special coordinates:

  1. The coordinate where the abscissa is 0, that is, the topmost coordinate
  2. The coordinate where the ordinate is 0, that is, the leftmost coordinate

Take the first type of coordinate out for analysis. Due to restrictions, the number of paths to this type of coordinate is:

numWays(0, j) = 1

It can be seen that the number of paths to reach such coordinates is the only one known. In the same way, the leftmost coordinate is also the only one knowable.

After knowing the total number of paths on the outermost two sides of the matrix, the total number of paths in each layer can be solved to find the total number of paths of all coordinates one by one.

Therefore, all the required information has been obtained and the solution can be written.

algorithm:
/**
 * 
 * @param {int} x 
 * @param {int} y 
 */
var twodimensional = function(x, y) {
    
    
  // construc numWays dp 2-dimensional-matrix
  var numWays = new Array()
  for (let i = 0; i < y; i++) {
    
    
    a[i] = new Array()
    for (let j = 0; j < x; j++) {
    
    
      a[i][j] = 0
    }
  }
  numWays[0][0] = 1

  // construct topmost ways
  for (let i = 1; i < x; i++) {
    
    
    numWays[0][i] = 1
  }

  // construct leftmost ways
  for (let i = 1; i < y; i++) {
    
    
    numWays[i][0] = 1
  }

  // find all ways
  for (let i = 1; i < x; i++) {
    
    
    for (let j = 1; j < y; j++ ) {
    
    
      numWays[i][j] = numWays[i - 1][j] + numWays[i][j - 1]
    }
  }
  
  return numWays[x - 1][y - 1]
}

Guess you like

Origin blog.csdn.net/qq_35714301/article/details/113614521