(matrix [][]int)
| 3 | import "math" |
| 4 | |
| 5 | func setZeroes(matrix [][]int) { |
| 6 | // Decide to use the first value of every row and column as the marker |
| 7 | // for whether the row or column should be set to 0 or not. |
| 8 | // Since matrix[0][0] can indicate that both 0-th row and column should |
| 9 | // be set to 0, we need a way to distinguish whether just the 0-th |
| 10 | // row and column should be set to 0. So, use matrix[0][0] to indicate |
| 11 | // if row 0 should be set to all zeros, and use an additional variable, |
| 12 | // setColZero to indicate if col 0 should be set to all zeros. |
| 13 | |
| 14 | setColZero := false |
| 15 | for r := 0; r < len(matrix); r++ { |
| 16 | for c := 0; c < len(matrix[r]); c++ { |
| 17 | v := matrix[r][c] |
| 18 | |
| 19 | // prevent any column 0 values in the rows from marking matrix[0][0] |
| 20 | // to 0, which indicates row 0 being marked for 0 |
| 21 | if v == 0 && c == 0 { |
| 22 | setColZero = true |
| 23 | continue |
| 24 | } |
| 25 | |
| 26 | if v == 0 { |
| 27 | // set the row marker to 0 |
| 28 | matrix[r][0] = 0 |
| 29 | |
| 30 | // set the column marker to 0 |
| 31 | matrix[0][c] = 0 |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // mark cell to 0 if it's row or column marker is 0, starting |
| 37 | // at matrix[1][1] and using the markers set earlier |
| 38 | for r := 1; r < len(matrix); r++ { |
| 39 | for c := 1; c < len(matrix[r]); c++ { |
| 40 | if matrix[r][0] == 0 || matrix[0][c] == 0 { |
| 41 | matrix[r][c] = 0 |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // mark row 0 with 0's |
| 47 | if matrix[0][0] == 0 { |
| 48 | for c := 0; c < len(matrix[0]); c++ { |
| 49 | matrix[0][c] = 0 |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // mark col 0 with 0's |
| 54 | if setColZero { |
| 55 | for r := 0; r < len(matrix); r++ { |
| 56 | matrix[r][0] = 0 |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Note: this was accepted into leetcode and uses O(1) space. |
| 62 | // There is a different solution that was hinted at that works |
no outgoing calls