question : Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.
Ans : the solution given is correct but when element variable is updated at different location it gives error and I can't understand why?
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int trow = matrix.size();
int tcol = matrix[0].size();
int rowIndex = 0;
int colIndex = tcol - 1;
int element = matrix[rowIndex][colIndex]; // already defined here
while(rowIndex < trow && colIndex >= 0){
element = matrix[rowIndex][colIndex]; // works here
if(element == target){
return 1;
}
if(element > target){
colIndex --;
}
if(element < target){
rowIndex ++;
}
// element = matrix[rowIndex][colIndex]; // this gives error here
}
return 0;
}
};
when element variable is updated at different location it gives error and I can't understand why?
Your while
loop condition ensures that at the start of the loop body, the indices rowIndex
and colIndex
are within the array bounds.
However, during the execution of the loop's body, one of these variables is updated with either colIndex--;
or rowIndex++;
. Once that has happened you cannot be sure the updated value is still within bounds, and so it is unsafe to use them at the end of the loop body to access matrix[rowIndex][colIndex]
. First the loop condition should be verified, and only if it is true, it is safe again to access matrix[rowIndex][colIndex]
.
If you access it at the end of the loop's body, it will go wrong when the matrix does not have the target value.
The most simple example is an array with just one row and column (so trow
and tcol
are both 1). Let's say matrix[0][0]
is 10, and the target value is 5. Then the loop will start with rowIndex
and colIndex
both equal to 0. element
will be 10. The comparison element > target
is true, so colIndex
is updated to become -1. Now it would be wrong to access matrix[rowIndex][colIndex]
as -1 is not a valid index. Instead the while
condition should be evaluated first, which would be false, and the function would return 0 (i.e., target was not found).
That's why the retrieval of matrix[rowIndex][colIndex]
needs to happen at the top of the loop body and not at the bottom of it.