Set Matrix Zeroes
Total Accepted: 67555 Total Submissions: 200621 Difficulty: Medium
Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Click to show follow up.
Subscribe to see which companies asked this question
Hide TagsArrayHide Similar Problems(M) Game of Life
Ideas:
0 1 2 5
4 3 1 4
0 1 0 4
1 2 1 3
2 0 1 1
(1) Set the first row, first column element to 0
0 0 0 5
4 3 1 4
0 1 0 4
1 2 1 3
0 0 1 1
(2) sets the row in [1,m-1],col in [1,n-1] whether the element is 0
0 0 0 5
4 0 0 4
0 0 0 0
1 0 0 3
0 0 0 0
(3) Final processing of first row, first column
0 00 0
0 0 0 4
0 0 0 0
0 0 0 3
0 0 0 0
Java code:
public Class Solution {public void setzeroes (int[][] matrix) {Boolean firstrow = False, Firstcol = false; int rows = Matrix.length; int cols = Matrix[0].length; for (int i=0;i<rows;i++) {for (int j=0;j<cols;j++) {if (matrix[i][j]==0) { if (i==0) FirstRow = true; if (j==0) Firstcol = true; MATRIX[I][0]=MATRIX[0][J] = 0; }}} for (int i=1;i<rows;i++) {for (int j=1;j<cols;j++) { if (matrix[i][0]==0 | | matrix[0][j]==0) MATRIX[I][J] = 0; }} if (FirstRow) for (int i=0;i<cols;i++) matrix[0][i] = 0; if (Firstcol) for (int j=0;j<rows;j++) matrix[j][0] = 0; }}
Leetcode:set Matrix Zeroes