Skip to content

Instantly share code, notes, and snippets.

@NicolaM94
Last active October 1, 2023 21:26
Show Gist options
  • Save NicolaM94/e053a95c65012cbe0c0a52d377f26654 to your computer and use it in GitHub Desktop.
Save NicolaM94/e053a95c65012cbe0c0a52d377f26654 to your computer and use it in GitHub Desktop.
Matrix 90° clockwise rotation (in place algorithm)
func invertArrayInPlace(array []int) []int {
for c := range array[:len(array)/2] {
temp := array[c]
array[c] = array[len(array)-c-1]
array[len(array)-1-c] = temp
}
return array
}
func InvertRows(matrix [][]int) [][]int {
for i, r := range matrix {
matrix[i] = invertArrayInPlace(r)
}
return matrix
}
func Transpose(matrix [][]int) [][]int {
for i := 0; i < len(matrix); i++ {
for j := i + 1; j < len(matrix); j++ {
temp := matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}
return matrix
}
func RotateClockwiseIP(matrix [][]int, deg int) [][]int {
matrix = Transpose(matrix)
matrix = InvertRows(matrix)
return matrix
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment