Aim: Change all the value of corresponding row and column to zero, if ever the matrix contains zero as one of the elements.
//declare variable to store start index containing value zero
int[] strtIndx;
//declare variable to store end index containing value zero
int[] endIndx ;
//variables as counters to make the corresponding row
//and column zero
int m = 0;
int n = 0;
//function to display matrix
public void DisplayMatrix(int[,] ary, int p, int q)
{
//Intialise start index and end index by matrix length
strtIndx = new int[ary.Length];
endIndx = new int[ary.Length];
//loop through two dimensional array
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
Console.Write(ary[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
}
//function to change the corresponding row and column to zero
public void matrix(int[,] ary, int p, int q)
{
strtIndx = new int[ary.Length];
endIndx = new int[ary.Length];
//p and q represents the dimension of array
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q;j++)
{
// Check for each value is equal to zero or not
if (ary[i, j] == 0)
{
//if true, store the first index to startindex
//and second index of two dimensional array to endindex
strtIndx[m] = i;
endIndx[n] = j;
//Increment the counter
m++;
n++;
}
}
}
//reset the value to zero
m = 0;
n = 0;
//loop through all elements and check for index equal to startindex and endindex
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
if (i == strtIndx[m])
{
//true, then set the value of that particular index zero
ary[i,j]=0;
}
if (j == endIndx[n])
{
ary[i, j] = 0;
}
}
}
//Input Matrix as
{ { 1, 2 }, { 3,0 }, { 5, 6 } } and dimensions as 3X2
ie, 1 2
3 0
5 6
Output: 1 0
0 0
5 0
Great..
ReplyDelete