Set Matrix Zeroes
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]Solutions
Last updated
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]Last updated
public class Solution
{
public void SetZeroes(int[][] matrix)
{
bool[] row = new bool[matrix.Length];
bool[] col = new bool[matrix[0].Length];
// Identify rows and columns that need to be set to zero
for (int i = 0; i < matrix.Length; i++) //N*M Times
{
for (int j = 0; j < matrix[0].Length; j++)
{
if (matrix[i][j] == 0)
{
row[i] = true;
col[j] = true;
}
}
}
// Set identified rows to zero
for (int i = 0; i < row.Length; i++)
{
if (row[i])
{
for (int j = 0; j < matrix[0].Length; j++)
{
matrix[i][j] = 0;
}
}
}
// Set identified columns to zero
for (int i = 0; i < col.Length; i++)
{
if (col[i])
{
for (int j = 0; j < matrix.Length; j++)
{
matrix[j][i] = 0;
}
}
}
}
}