Between Python and c++ 2d array initialization. What is this ? and why?

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

I came up with the solution and did my code in C++, my native programming language.

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> matrix(m, vector<int>(n, 0));
        for (int i = 0; i < m; i++) {
            matrix[i][0] = 1;
        }
        for (int j = 0; j < n; j++) {
            matrix[0][j] = 1;
        }
        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                matrix[i][j] = matrix[i][j-1] + matrix[i-1][j];
                
            }
        }
        return matrix[m-1][n-1];
    }
};

The 2d vector being initialized as arr[m][n]

As I am learning Python I decided to solve it in Python as well. I faced an absurd problem. Here,

arr = [[0 for x in range(n)] for y in range(m)] 

I initialised the 2d array as

arr = [[0 for x in range(m)] for y in range(n)] 

and, I was getting Error-List index out of range. I really got screwed up figuring out this needle from the hay, but anyway I got it. Can you please explain why these clashes between rows and columns even though everything is the same?

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        if m == 0 or n == 0:
            return 0
        arr = [[0 for x in range(n)] for y in range(m)] 
        for i in range(m):
            arr[i][0] = 1
        for j in range(n):
            arr[0][j] = 1
        for i in range(1,m):
            for j in range(1,n):
                arr[i][j] = arr[i][j-1] + arr[i-1][j]
        return arr[m-1][n-1]    

Here is the question link for reference: Unique paths-leetcode

1 answer

  • answered 2020-06-27 05:44 jignatius

    In your C++ code:

    vector<vector<int>> matrix(m, vector<int>(n, 0));
    

    you're creating a vector of m vectors each containing n elements initialised to 0. That's like a 2d matrix of m rows x n columns.

    The equivalent code in Python is:

    arr = [[0 for x in range(n)] for y in range(m)]
    

    which is a list comprehension. This syntax looks back to front for people coming from a C++ background, but the format for list comprehension is:

    [ expression for item in list if conditional ]
    

    So in your case for every index in the range 0 to m you create an inner list containing n zeroes, i.e. a m x n matrix.

    This code:

    arr = [[0 for x in range(m)] for y in range(n)]
    

    is not equivalent to your C++ code. It's producing a list of n lists, each containing m zeroes, i.e. a n x m matrix. Hence the errors you got.