Wednesday 24 September 2014

SETTING THE ELEMENTS OF A PARTICULAR ROW AND COLUMN TO ZERO

Given a 2-D Matrix, if an element of the matrix is zero, all elements of the corresponding row and column are set to ZERO.

In the solution to this question,  a duplicate matrix has been created and by traversing the elements of
the original matrix, changes in the duplicate matrix are made accordingly.

For example,
         For a given 3x3 matrix:
                            1 2 3
                            4 0 5
                            9 7 0
         The matrix set to zero would be,
                            1 0 0
                            0 0 0
                            0 0 0

Source Code:-
*****************************************************************

#include<stdio.h>
#include<stdlib.h>

/*function which takes the original matrix,creates its duplicate and sets
   the required elements to zero in the duplicate matrix*/

  int ** setZero(int **arr,int m,int n)
 {
    int **arr1,i,j,k;
    arr1=(int**)malloc(sizeof(int*)*m);//allocating memory to duplicate matrix.
    for(i=0;i<m;i++)
        arr1[i]=(int*)malloc(sizeof(int)*n);
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            arr1[i][j]=arr[i][j];

    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            if(arr[i][j]==0)
            {
                for(k=0;k<m;k++)
                    arr1[k][j]=0;
                for(k=0;k<n;k++)
                    arr1[i][k]=0;
            }
        }
    }
    return arr1;
}

int main()
{
    int **arr,m,n,i,j,**arr1;
    printf("\nEnter the no of rows:");
    scanf("%d",&m);
    printf("\nEnter the no of columns:");
    scanf("%d",&n);
    arr=(int**)malloc(sizeof(int*)*m);
    for(i=0;i<m;i++)
        arr[i]=(int*)malloc(sizeof(int)*n);

    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            scanf("%d",&arr[i][j]);

    arr1=setZero(arr,m,n);

//the original matrix is kept intact and the changes are done in the duplicate one i.e. arr1.

    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
            printf("%d",arr1[i][j]);//printing of elements of duplicate matrix i.e. arr1.
        printf("\n");
    }
    return 0;
}


*****************************************************************

No comments:

Post a Comment