Leetcode - Longest Repeating Character Replacement
Leetcode - Game of Life

Leetcode - Set Matrix Zeroes

violet posted @ Apr 06, 2020 06:41:47 AM in 算法 with tags Algorithm Golang array , 178 阅读

https://leetcode.com/problems/set-matrix-zeroes/

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

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

 

1. If meet a 0, set first column or first row to 0. If the first row or column is 0, use two variables to mark it.

2. Loop from 1, if the first column or the first row is 0, mark the current element to 0

3. If the first row is 0, loop the column and mark 0; if the first column is 0, loop the row and mark 0.

func setZeroes(matrix [][]int)  {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return
    }
    row := len(matrix)
    column := len(matrix[0])
    firstRow := false
    firstColumn := false
    
    for i := 0; i < row; i++ {
        for j := 0; j < column; j++ {
            if matrix[i][j] == 0 {
                if i == 0 {
                    firstRow = true
                }
                if j == 0 {
                    firstColumn = true
                }
                matrix[0][j] = 0
                matrix[i][0] = 0
            }
        }
    }
    for i := 1; i < row; i++ {
        for j := 1; j < column; j++ {
            if matrix[i][0] == 0 || matrix[0][j] == 0 {
                matrix[i][j] = 0
            }
        }
    }
    if firstRow {
        for j := 0; j < column; j++ {
            matrix[0][j] = 0
        }
    }
    if firstColumn {
        for i := 0; i < row; i++ {
            matrix[i][0] = 0
        }
    }
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter