Set Matrix Zeroes
Last updated
Last updated
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example 1:
Example 2:
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Steps
Initialize two boolean arrays row
and col
: These arrays are used to keep track of which rows and columns have at least one zero. The size of row
is the number of rows in the matrix, and the size of col
is the number of columns.
Identify rows and columns that need to be set to zero: This is done by iterating over each element in the matrix. If an element is zero, the corresponding entries in the row
and col
arrays are set to true
.
Set identified rows to zero: For each true
entry in the row
array, set all elements in that row of the matrix to zero.
Set identified columns to zero: Similarly, for each true
entry in the col
array, set all elements in that column of the matrix to zero.
Complexity
Time complexity: O(N*M)
Space complexity: O(N+M)