You can use the first row and column as a scratchpad to keep track of
which rows and columns need to be 1.

Make one pass over the matrix to put 1's in the scratchpad locations.
Then make a second pass checking the scratchpad to see of the square
needs to be flipped to a 1.

To make this scratchpad available we need 2 int variables to keep
track of whether row 0 and col 0 should finally become 1's.

// Set row 0 and col 1 scratchpads.
row_0 = col_0 = 0;
for (i = 0; i < m; i++)
  if (a[i][0]) { col_0 = 1; break; }
for (j = 0; j < n; j++)
  if (a[0][j]) { row_0 = 1; break; }

// Set scratchpad for other rows and columns.
for (i = 1; i < m; i++)
  for (j = 1; j < n; j++)
    if (a[i][j]) a[i][0] = a[0][j] = 1;

// Use scratch pad to fill in rest of matrix
for (i = 1; i < m; i++)
  for (j = 1; j < n; j++)
    if (a[0][j] || a[i][0]) a[i][j] = 1;

// fill in row 0 and col 0 as needed.
if (row_0) for (j = 0; j < n; j++) a[0][j] = 1;
if (col_0) for (i = 0; i < n; i++) a[i][0] = 1;

On Aug 31, 9:40 am, manish kapur <manishkapur.n...@gmail.com> wrote:
> Input is a matrix of size n x m of 0s and 1s.
>
> eg:
> 1 0 0 1
> 0 0 1 0
> 0 0 0 0
>
> If a location has 1; make all the elements of that row and column = 1. eg
>
> 1 1 1 1
> 1 1 1 1
> 1 0 1 1
>
> Solution should be with Time complexity = O(n*m) and O(1) extra space

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to