Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
1: /// <summary>
2: /// Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
3: /// </summary>
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: Program p = new Program();
9: int[,] matrix = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 0 }, { 9, 10, 11, 0 } };
10: p.SetColumnAndRowWithZeroWhileElementIsZero(ref matrix);
11: PrintMatrix(matrix);
12: Console.ReadKey();
13: }
14:
15: public void SetColumnAndRowWithZeroWhileElementIsZero(ref int[,] matrix)
16: {
17: int line = matrix.GetLength(0);
18: int column = matrix.GetLength(1);
19: if (line == 0 || column == 0)
20: {
21: return;
22: }
23:
24: int[] rows = new int[line];
25: int[] colums = new int[column];
26:
27: //mark the row or column which will be set to zero
28: for (int i = 0; i < line; i++)
29: {
30: for (int j = 0; j < column; j++)
31: {
32: if (matrix[i, j] == 0)
33: {
34: rows[i] = 1;
35: colums[j] = 1;
36: }
37: }
38: }
39:
40: for (int i = 0; i < line; i++)
41: {
42: for (int j = 0; j < column; j++)
43: {
44: if (rows[i] == 1 || colums[j] == 1)
45: {
46: matrix[i, j] = 0;
47: }
48: }
49: }
50: }
51: /// <summary>
52: /// Print the matrix to console
53: /// </summary>
54: public static void PrintMatrix(int[,] matrix)
55: {
56: int line = matrix.GetLength(0);
57: int column = matrix.GetLength(1);
58: if (line == 0 || column == 0)
59: {
60: Console.WriteLine("empty array!");
61: }
62: else
63: {
64: Console.WriteLine("lines:" + line.ToString());
65: Console.WriteLine("columns:" + column.ToString());
66: }
67: for (int i = 0; i < line; i++)
68: {
69: Console.WriteLine();
70: for (int j = 0; j < column; j++)
71: {
72: Console.Write(matrix[i, j].ToString().PadLeft(5));
73: Console.Write(" ");
74: }
75: }
76: }
77: }