Setting row and column to zeros

You are given a 2-dimensional integer array Arr[M][N]. A few of the
elements in this array are zero. Write an algorithm such that if
A[i][j] is zero, all the elements in row i and all the elements in
column j should be set to 0. In other words, if any element is zero,
its entire row and column should be zero.

Answer:


Solution in O(mn) time.

Step 1: Init array[m] = {-1}

Step 2:
for ( i = 0; i< m; ++i )
for ( j = 0; j < n; ++j)
{
if ( matrix[i][j] == 0 )
array[i] = j;
break;
}

Complexity : O(mn)

step 3:
for ( k = 0; k < m; ++k)
{
if(array[k] != -1)
{
for( i = 0; i < m; ++i)
matrix[k][i] = 0;
for( i = 0; i < n ; ++i)
matrix[i][array[k]] = 0;
}
}

complexity: O(m(m+n))

Total complexity = O(mn) + O(m^2) + O(n)



No comments: