【问题标题】:Find number of paths in a 2d binary array (C)查找二维二进制数组中的路径数 (C)
【发布时间】:2014-05-06 03:23:28
【问题描述】:

我在一次采访中被问到这个问题,并且一直在努力寻找一个优雅的解决方案(用 C 语言),问题陈述:

  • 给您一个包含 M 行和 N 列的二维数组。
  • 您最初位于 (0,0),它是 数组。
  • 您可以向右或向下移动。
  • 数组用 1 和 0 填充。 1 表示可以移动 通过该单元格,0 表示您无法通过该单元格 细胞。

在 C 'numberOfPaths' 中写一个函数,它接受上述二维数组,返回从左上角单元格到右下角单元格的有效路径数(即 [0,0] 到 [M-1 ,N-1])。

编辑:忘了提到要求是递归解决方案

帮助将不胜感激! 谢谢

【问题讨论】:

  • 使用 DFS 的答案有帮助吗?

标签: c arrays


【解决方案1】:

如果您正在寻找递归解决方案,您可以使用 DFS。

DFS (array, x, y)
{
if (array [x][y]==0 || x>M || y>N){
    return;
}
if (x==M && y==N){
    count++;
    return;
}
DFS (array, x, y+1);
DFS (array, x+1, y);
}

【讨论】:

  • 谢谢!这很有帮助。
【解决方案2】:

到给定点的路径数就是到上面点的路径数加上到左边点的路径数。所以,伪代码大概是:

num_paths[0][0] = 1;
for (x = 0; x < M; ++x)
   for (y = 0; y < N; ++y)
      if (!allowed_through[x][y])
         num_paths[x][y] = 0;
      else
         num_paths[x][y] = num_paths[x-1][y] + num_paths[x][y-1];

您需要 x=0 和 y=0 的特殊情况,否则,我认为应该这样做。

【讨论】:

    【解决方案3】:
    #include <stdio.h>
    
    int count=0;
    int maxrows = 10;
    int maxcols = 10;
    int M, N;
    
    void DFS (int array[][10], int x, int y)
    {
    int r, c;
    
    /* process element at input row and column */
    
    if (array [x][y]==0 || x>M || y>N){
    /* no path forward; return */
        return;
    }
    if (x==M-1 && y==N-1){
        /* found path; increment count */
        count++;
        return;
    }
    /* recurse: to matrix starting from same row, next column */
    r = x;
    c = y +1;
    if (c < N-1) {
        DFS (array, r,c);
    } else {
        /* if last column - check to see  */
        /* if rest of rows in last column allow for a path */
        int tr = r;
        while ( tr <= M-1)  {
            if (array[tr][c] == 1) {
                tr++;
            }       
            else {
                return;
            }
        }
        /* reached last node - path exists! */
        count++;
    }
    /* recurse: to matrix starting from next row, same column */
    r = x+1;
    c = y;
    if (r < M-1) {
        DFS (array, r,c);
    } else {
        /* if last row - check to see  */
        /* if rest of columns in last row allow for a path */
        int tc = c;
        while ( tc <= N-1)  {
            if (array[r][tc] == 1) {
                tc++;
            } else {
                return;
            }
        }
        /* reached last node - path exists! */
        count++;
    }
    }
    
    int main () {
    int i, j;
        scanf("%d %d",&M,&N);
        int a[10][10] = {};
    int row, col;
    
        for(i=0;i<M;i++)
                for(j=0;j<N;j++)
                        scanf("%d", &a[i][j]);
        if ((M > maxrows) || (N > maxcols)) {
        printf("max of 10 rows and 10 cols allowed for input\n");
            return (-1);
        };
    /* print input matrix */
        for(row=0;row<M;row++) {
                for(col=0;col<N;col++){
                        printf("%d ",a[row][col]);
                }
                printf(" EOR\n");
        }
    DFS(a,0,0);
        printf("number of paths is %d\n", count);
        return 0;
    }
    

    【讨论】:

      【解决方案4】:

      在打印所有路径之前,请先尝试此功能。 如果向量 Out 的大小为 0 则路径数为 0,但如果 size(Out) > 0 则向量节点的大小 + 1 为从左上角到右下角的路径总数。

      #include <iostream>
      #include <vector>
      
      using namespace std;
      
      typedef vector<pair<int,int> > vPii;
      
      bool pathTL2BR( int Arr2D[][4], vPii &Out, vPii &Nodes, 
                      int _x,int _y, int _M, int _N)
      {
          bool out1 = false;
          bool out2 = false;
          if( Arr2D[_x][_y] == 1 )
          {
              if( _y+1 < _N )
                  out1 = pathTL2BR( Arr2D, Out, Nodes, _x, _y+1, _M, _N);
      
              if( _x+1 < _M )
                  out2 = pathTL2BR( Arr2D, Out, Nodes, _x+1, _y, _M, _N);
      
              if( (out1 || out2) ||
                  ( (_x == (_M-1)) && (_y == (_N-1)) ) )
              {
                  if(out1 && out2)
                      Nodes.push_back( make_pair(_x,_y ) );
                  Out.push_back( make_pair(_x,_y ) );
                  return true;
              }
              else
                  return false;
          }
          else
              return false;
      }
      
      // Driver program to test above function
      int main()
      {
          int Arr2D[][4] = {
                          {1,1,1,1},
                          {0,1,0,1},
                          {0,1,0,1},
                          {0,1,0,1}
                          };
      
          vPii Out;
          vPii Nodes;
          vector<vPii> Output;
          pathTL2BR( Arr2D, Out, Nodes, 0, 0, 4, 4);
      
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        这是一个 python 解决方案,我已经在 cmets 中做了解释。

        def find_num_paths(arr_2D, i, j):
        # i,j is the start point and you have to travel all the way back to 0,0
            if i == j and i == 0:
                return 1 # you have reached the start point
        
            if i < 0 or j < 0 or arr_2D[i][j] == 0: # out of range or no path from that point
                return 0
        
            if arr_2D[i][j] == 1:
                return find_num_paths(arr_2D, i, j-1) + find_num_paths(arr_2D, i-1, j) + find_num_paths(arr_2D, i-1, j-1) # you could go one step above, to the left or diagonally up.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多