I had inserted 0 instead of 1 The corrected code will be:
 public static void setZeros(int[][] matrix) {
   int[] row = new int[matrix.length];
   int[] column = new int[matrix[0].length];
   // Store the row and column index with value 0
     for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length;j++) {
            if (matrix[i][j] == 1) {
                  row[i] = 1;
                  column[j] = 1;
          }
      }

 }

  // Set arr[i][j] to 0 if either row i or column j has a 0
           for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if ((row[i] == 1 || column[j] == 1)) {
                   matrix[i][j] = 1;
                }
          }
      }

On Oct 3, 11:06 pm, Shruti Gupta <shruti.gupt...@gmail.com> wrote:
> Hi!
> A effecient way to solve the problem in O(1) space is by making use of
> the fact that instead of keeping track of which cell has a 0, we can
> just know which row or column has zero, as eventually that row/col
> will become 0. The code looks like this:
>
> public static void setZeros(int[][] matrix) {
>   int[] row = new int[matrix.length];
>   int[] column = new int[matrix[0].length];
>   // Store the row and column index with value 0
>     for (int i = 0; i < matrix.length; i++) {
>        for (int j = 0; j < matrix[0].length;j++) {
>            if (matrix[i][j] == 0) {
>                  row[i] = 1;
>                  column[j] = 1;
>          }
>      }
>
> }
>
>  // Set arr[i][j] to 0 if either row i or column j has a 0
>           for (int i = 0; i < matrix.length; i++) {
>            for (int j = 0; j < matrix[0].length; j++) {
>                if ((row[i] == 1 || column[j] == 1)) {
>                   matrix[i][j] = 0;
>                }
>          }
>      }
>
> Thus there is no extra space taken.
>
> Shruti
>
> On Oct 3, 12:27 am, rahul sharma <rahul23111...@gmail.com> wrote:
>
>
>
>
>
>
>
> > nput 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