Today We will write a program for converting matrix’s row and columns to zero if any one element is zero.
Example
Input | Output |
2 2 2 2 2 0 2 3 2 2 2 2 |
2 0 2 2 0 0 0 0 2 0 2 2 |
Code
public static void RowColumnZero(int[,] matrix) { Console.WriteLine("------------------------------------------------------"); Console.WriteLine("Before"); Print2DMatrix(matrix); int rowConter; int columnCounter; rowConter = columnCounter = 0; int[] rowArray = new int[matrix.GetLength(0)]; int[] columnArray = new int[matrix.GetLength(1)]; for (rowConter = 0; rowConter < rowArray.Length; rowConter++) { for (columnCounter = 0; columnCounter < columnArray.Length;
columnCounter++) { if (matrix[rowConter, columnCounter] == 0) { rowArray[rowConter] = 1; columnArray[columnCounter] = 1; } } } for (rowConter = 0; rowConter < rowArray.Length; rowConter++) { for (columnCounter = 0; columnCounter < columnArray.Length;
columnCounter++) { if (rowArray[rowConter] == 1 || columnArray[columnCounter] == 1) { matrix[rowConter, columnCounter] = 0; } } } //Print output Console.WriteLine("After"); Print2DMatrix(matrix); Console.WriteLine("------------------------------------------------------");
}
Program For Creating the Matrix
public static int[,] CreateTestMatrix(int row, int column) { int[,] matrix = new int[row, column]; int i, j; Random rnd = new Random(); for (i = 0; i < row; i++) { //create a test matrix for (j = 0; j < column; j++) { matrix[i, j] = rnd.Next(0, row * column); } } return matrix; }
Program for Printing the Matrix
private static void Print2DMatrix(int[,] matrix) { for (int rowConter = 0; rowConter < matrix.GetLength(0); rowConter++) { { for (int columnCounter = 0; columnCounter < matrix.GetLength(1);
columnCounter++) { Console.Write(matrix[rowConter, columnCounter] + " "); } Console.WriteLine(Environment.NewLine); } } }
Test
Input | Output |
6 0 9 11 7 3 10 5 10 5 11 3 |
0 0 0 0 7 0 10 5 10 0 11 3 |
7 8 5 3 8 8 11 19 15 19 0 19 7 7 9 11 14 8 16 6 |
7 8 0 3 8 8 0 19 0 0 0 0 7 7 0 11 14 8 0 6 |
6 0 3 5 5 3 6 8 6 |
0 0 0 5 0 3 6 0 6 |
5 11 6 8 9 5 7 5 13 7 1 7 0 12 9 12 |
0 11 6 8 0 5 7 5 0 7 1 7 0 0 0 0 |
2 6 3 4 5 3 4 3 7 |
2 6 3 4 5 3 4 3 7 |
1 1 3 1 |
1 1 3 1 |
Filed under:
Array
Leave a comment