Saturday, January 5, 2013

Unique path With obstacles

Solution:

DP solution:


class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        int st[m][n];
        for (int i = 0; i < m ; i++) {
            if (obstacleGrid[i][0] == 1)
            {
                while (i < m) {
                    st[i][0] = 0;
                    i++;
                }
            } else {
                st[i][0] = 1;
            }
        }
        for (int i = 0; i < n ; i++) {
            if (obstacleGrid[0][i] == 1) {
                while (i < n) {
                    st[0][i] = 0;
                    i++;
                }
            } else {
                st[0][i] = 1;
            }
        }
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (obstacleGrid[i][j] == 1)
                    st[i][j] = 0;
                else
                    st[i][j] = st[i-1][j] + st[i][j-1];
     
        return st[m-1][n-1];
    }
};

No comments:

Post a Comment