Given a matrix of size n x m filled with 0\'s and 1\'s
e.g.:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
if the matrix has 1 a
Assuming matrix is 0-based, i.e. the first element is at mat[0][0]
Use the first row and first column as table headers to contain column and row info respectively. 1.1 Note the element at mat[0][0]. If it is 1, it will require special handling at the end (described later)
Now, start scanning the inner matrix from index[1][1] up to the last element 2.1 If the element at[row][col] == 1 then update the table header data as follows Row: mat[row][0] = 1; Column: mat[0][col] = 1;
At this point we have the complete info on which column and row should be set to 1
At this point we have processed all the cells in the inner matrix and we are yet to process the table header itself
Time complexity O(2*((n-1)(m-1)+(n+m-1)), i.e. O(2*n*m - (n+m) + 1), i.e. O(2*n*m) Space O(1)
See my implementation at http://codepad.org/fycIyflw