Set the matrix of LeetCode [73] to zero
Title Description
Given a matrix of m x n, if an element is 0, then all elements of the row and column it is in are set to 0. Please use the in place algorithm.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Title Analysis
This problem is to find the index of 0, and then assign all rows and columns of the index to 0. My personal approach is to create a new boolean matrix, and remember that point of 0 as true, and others as default. Then traverse the matrix, find the index value of true, and change the number in the original matrix.
Source code
class Solution { public void setZeroes(int[][] matrix) { int row=matrix.length; int col=matrix[0].length; boolean[][] tep=new boolean[row][col]; //Set matrix record index for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(matrix[i][j]==0){ tep[i][j]=true; } } } //Go back to the original matrix, change the value of the row and column for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(tep[i][j]){ for(int r=0;r<row;r++){ matrix[r][j]=0; } for(int c=0;c<col;c++){ matrix[i][c]=0; } } } } } }
Improvement
This method is a stupid method, which consumes a lot of time and space, so we should skip the step of recording index to matrix, and create Boolean value only to record whether the first row and first column need to be set to 0. Then start from (1, 1) and traverse the search again.
Improved code
class Solution { public void setZeroes(int[][] matrix) { boolean rowFlag = false; //Judgement first line for (int i = 0; i < matrix[0].length; i++) { if (matrix[0][i] == 0) { rowFlag = true; break; } } boolean colFlag = false; for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] == 0) { colFlag = true; break; } } for (int i = 1; i < matrix.length; i++) { for (int j = 1; j < matrix[0].length; j++) { if (matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < matrix[0].length; i++) { if (matrix[0][i] == 0) { for (int j = 0; j < matrix.length; j++) { matrix[j][i] = 0; } } } for (int i = 1; i < matrix.length; i++) { if (matrix[i][0] == 0) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = 0; } } } if (rowFlag){ for (int i = 0; i < matrix[0].length; i++) { matrix[0][i] = 0; } } if (colFlag){ for (int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } }
}
Analysis
The first time complexity is O (n^3), and the space complexity is greater than the second method because of the new address
The second is O (n^2)
difficulty
It's easy to find the way of thinking. Generally, you know how to start after reading the questions, but you still need to think more about the complexity of time and space.
Summary
To meet a matrix is nothing more than to traverse and find an index, which is to think about how to reduce the complexity.
[1]https://leetcode-cn.com/problems/set-matrix-zeroes/comments/