This question comes from geekforgeek: http://www.geeksforgeeks.org/find-k-such-that-all-elements-in-kth-row-are-0-and-kth-column-are-1-in-a-boolean-matrix/
Given a square boolean matrix mat[n][n], find k such that all elements in k’th row are 0 and all elements in k’th column are 1. The value of mat[k][k] can be anything (either 0 or 1). If no such k exists, return -1. Do it in O(n) time.
Note there is only one such k can satisfy the rules.
Simple way is to do that is to find a kth row that all values are 0s except the kth element. Then check the kth column if all values are 1s except the kth element. This requires us to check all of the element. Time complexity: O(n*n)
Another way to travel from top-left corner, we start with 0th row:
go right if the element is 0, if we reach the end of row, then that means: 1) this rth row is potential candidate; 2) the columns/rows from r+1 to n-1 are not candidate; And we check kth row/col values.
go down if the element is 1, for the current row is no longer qualifies.
Since we either go right or go down, then time complexity is O(n)
public static int findKthRow(int[][] mat){
int n = mat.length;
int row = 0;
while(row<n-1){
int col = row + 1;
//move from left to right at current row
while(col<n && mat[row][col] == 0){
col++;
}
/*
* if we reach the last column of current row, then
* this row is candidate and
* rest of rows are not candidates
* otherwise
* we go down one row below
*/
if(col == n){
//check if this row is qualified
return checkKthRowCol(mat, row)?row:-1;
}else{
row++;
}
}
return checkKthRowCol(mat, row)?row:-1;
}
private static boolean checkKthRowCol(int[][] mat, int k){
int n = mat.length;
for(int i = 0; i<n; i++){
if(i==k)
continue;
else{
if(mat[k][i]==1 || mat[i][k]==0)
return false;
}
}
return true;
}
This is a very nice code. I think you can change "row++" to "row=col"
ReplyDelete