Skip to content

Instantly share code, notes, and snippets.

@onema
Created April 14, 2015 17:59
Show Gist options
  • Save onema/d99521cc7ea144e6ff10 to your computer and use it in GitHub Desktop.
Save onema/d99521cc7ea144e6ff10 to your computer and use it in GitHub Desktop.
An algorithm that sets in an MxN matrix the entire row and column to 0 if an element is 0.
/**
* Problem: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
* Not a very elegant solution but it gets the job done on my way to learn go!
*/
// zerome_out.go
package main
import (
"fmt"
)
func main() {
matrix := [][]int{
{1, 1, 2, 3, 4},
{6, 7, 8, 1, 6},
{4, 5, 0, 7, 9},
{1, 2, 3, 4, 5},
{3, 1, 5, 6, 1},
}
PrintMatrix(matrix)
matrixWithZeros := ZeroMeOut(matrix)
fmt.Println("=======================\n")
PrintMatrix(matrixWithZeros)
}
func ZeroMeOut(matrix [][]int) [][]int {
y := len(matrix)
x := len(matrix[0])
var zeroLocations [][]int
// Find all the zeros in the matrix and save the position
for i, row := range matrix {
for j := range row {
if matrix[i][j] == 0 {
location := []int{i, j}
zeroLocations = append(zeroLocations, location)
}
}
}
// Use the positions to turn the corresponding row and column to zeros
for _, element := range zeroLocations {
i := element[0]
j := element[1]
for column := 0; column < x; column++ {
matrix[i][column] = 0
}
for row := 0; row < y; row++ {
matrix[row][j] = 0
}
}
return matrix
}
func PrintMatrix(matrix [][]int) {
for _, row := range matrix {
for _, value := range row {
fmt.Print(int(value))
}
fmt.Println("\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment