2021-04-01: Given a square matrix, adjust it to rotate 90 degrees clockwise. [[a,b,

2021-04-01: Given a square matrix, adjust it to rotate 90 degrees clockwise. [[a,b,c],[d,e,f],[g,h,i]] becomes [[g,d,a],[h,e,b],[i,f,c ]].

Fu Da's answer 2021-04-01:

Four numbers exchange. Exchange the outer circle first, then the inner circle.

The code is written in golang. code show as below:

package main

import "fmt"

func main() {
    matrix := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
    printMatrix(matrix)
    rotate(matrix)
    printMatrix(matrix)
}

func rotate(matrix [][]int) {
    matrixLen := len(matrix)
    if matrixLen <= 1 {
        return
    }
    a := 0             //左上行
    b := 0             //左上列
    c := matrixLen - 1 //右下行
    d := c             //右下列

    //左上 右上 右下 左下
    //a,b  a,d  c,d  c,b
    for a < c {
        for j := a; j < c; j++ {
            //四数交换
            matrix[a][b+j], matrix[a+j][d], matrix[c][d-j], matrix[c-j][b] = matrix[a+j][d], matrix[c][d-j], matrix[c-j][b], matrix[a][b+j]
        }
        a++
        b++
        c--
        d--
    }

}
func printMatrix(matrix [][]int) {
    for i := 0; i < len(matrix); i++ {
        for j := 0; j < len(matrix[0]); j++ {
            fmt.Print(matrix[i][j], "\t")
        }
        fmt.Println("")
    }
    fmt.Println("-----------")
}

The execution results are as follows:
Insert picture description here


Left God java code
comment

Guess you like

Origin blog.51cto.com/14891145/2679971