1. 程式人生 > >Leetcode 73: Set Matrix Zeroes

Leetcode 73: Set Matrix Zeroes

its in place lac false str har tle trick clas

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Note: it‘s a pretty tricky problem, hard to be bug free.

 1 public class Solution {
 2     public void SetZeroes(int[,] matrix) {
 3         int m = matrix.GetLength(0), n = matrix.GetLength(1);
 4         
 5
bool firstColumn = false; 6 for (int i = 0; i < m; i++) 7 { 8 if (matrix[i, 0] == 0) 9 { 10 firstColumn = true; 11 break; 12 } 13 } 14 15 for (int i = 0; i < m; i++) 16 {
17 for (int j = 1; j < n; j++) 18 { 19 if (matrix[i, j] == 0) 20 { 21 matrix[i, 0] = 0; 22 matrix[0, j] = 0; 23 } 24 } 25 } 26 27 for (int i = m - 1; i >= 0
; i--) 28 { 29 for (int j = n - 1; j >= 1; j--) 30 { 31 if (matrix[i, 0] == 0 || matrix[0, j] == 0) 32 { 33 matrix[i, j] = 0; 34 } 35 } 36 37 if (firstColumn) matrix[i, 0] = 0; 38 } 39 } 40 }

Leetcode 73: Set Matrix Zeroes