educative.io

Educative

I think there is a different flavor of the same solution with just one pass over the matrix

Something like this:

public static int uniquePathsWithObstacles(int[][] obstacleGrid) {    		
		if(obstacleGrid[0][0] == 1) {
			return 0;
		}

		for(int i = 0; i < obstacleGrid.length; i++) {
			for(int j = 0; j < obstacleGrid[0].length; j++) {
				if(obstacleGrid[i][j] == 1) {
					obstacleGrid[i][j] = 0;
					continue;
				}
				obstacleGrid[i][j] = 1;
				int n = 0;
				if(i - 1 >= 0) {
					n += obstacleGrid[i-1][j];
				}
				if(j - 1 >= 0) {
					n += obstacleGrid[i][j-1];
				}
				obstacleGrid[i][j] = n > 0? n: obstacleGrid[i][j];
			}
		}

		return obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1];
	}

Type your question above this line.

Course: https://www.educative.io/collection/5642554087309312/5679846214598656
Lesson: https://www.educative.io/collection/page/5642554087309312/5679846214598656/5773441717764096

Hi @Peter_Litvak,

Yes your solution is correct, perhaps more simpler than the one provided in lesson :slightly_smiling_face:.

Thank you.