1. 程式人生 > >實現二維數組順時針旋轉的功能

實現二維數組順時針旋轉的功能

style bsp 維數 spa [] time 二維 sting div

用GO實現二維數組的順時針旋轉,總體思想為,確定好正方形二維數組的邊界,從邊開始旋轉,轉完整個邊界之後把二維數組向內縮小一個邊界,找到邊界,繼續旋轉(交換)....

例如:

{ 1, 2, 3, 4}

{ 5, 6, 7, 8}

{ 9,10,11,12}

{13,14,15,16}

旋轉後:

{13, 9, 5, 1}

{14,10, 6, 2}

{15,11, 7, 3}

{16,12, 8, 4}

 1 package algorithm
 2 
 3 func rotateSquare(arr *[][]int) {
 4     topLeftRow := 0
5 topLeftCol := 0 6 lowRightRow := len(*arr) - 1 7 lowRightCol := len((*arr)[0]) - 1 8 for ; topLeftRow <= lowRightRow && topLeftCol <= lowRightCol; { 9 rotateEdge(arr, topLeftRow, topLeftCol, lowRightRow, lowRightCol) 10 topLeftRow++ 11 topLeftCol++ 12
lowRightRow-- 13 lowRightCol-- 14 } 15 } 16 17 func rotateEdge(arr *[][]int, topLeftRow, topLeftCol, lowRightRow, lowRightCol int) { 18 times := lowRightCol - topLeftCol 19 for i := 0; i < times; i++ { 20 origin := (*arr)[topLeftRow][topLeftCol+i] 21 (*arr)[topLeftRow][topLeftCol+i] = (*arr)[lowRightRow-i][topLeftCol]
22 (*arr)[lowRightRow-i][topLeftCol] = (*arr)[lowRightRow][lowRightCol-i] 23 (*arr)[lowRightRow][lowRightCol-i] = (*arr)[topLeftRow+i][lowRightCol] 24 (*arr)[topLeftRow+i][lowRightCol] = origin 25 } 26 }

測試代碼為

 1 package algorithm
 2 
 3 import (
 4     "testing"
 5     "fmt"
 6 )
 7 
 8 func Test_rotateSquare(t *testing.T) {
 9     arr := [][]int{
10         {1, 2, 3, 4},
11         {5, 6, 7, 8},
12         {9, 10, 11, 12},
13         {13, 14, 15, 16},
14     }
15     rotateSquare(&arr)
16     fmt.Println(arr)
17 }

實現二維數組順時針旋轉的功能