Array rotation problem, leetcode: 48

Array elements rotate clockwise

leetcode: 48. Rotate image

Medium difficulty

Given an n × n two-dimensional matrix represents an image.

Rotate the image 90 degrees clockwise.

Description:

You have to rotate the image **in place **, which means you need to modify the input 2D matrix directly. Please do not use another matrix to rotate the image.

Example 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

Problem-solving ideas:

Understand the essence of the problem—>Abstract the big problem, summarize the law of change—>Realize—>Optimize operation speed

Array is divided into units by circle
Insert picture description here

Determine the coordinates of the upper left and lower right corners, and then "shrink the circle"
Insert picture description here

Rotate the elements of each layer at right angles

Insert picture description here

The inner elements are operated with the outer elements. Until startX>endX

Insert picture description here

Test code:

package main

import "fmt"

func main() {
    
    
	print := func(nums [][]int) {
    
    
		for _, v := range nums {
    
    
			for _, n := range v {
    
    
				fmt.Print("\t", n)
			}
			fmt.Println()
		}
		fmt.Println("---------------")
	}

	nums := [][]int{
    
    {
    
    1, 2, 3, 4}, {
    
    5, 6, 7, 8}, {
    
    9, 10, 11, 12}, {
    
    13, 14, 15, 16}}

	print(nums)
	startX ,startY, endX ,endY := 0,0,len(nums[0]) - 1, len(nums[0]) - 1
	for startX < endX {
    
    
		for i := 0; i < endX-startX; i++ {
    
    
			nums[startX][startY+i], nums[endX-i][startY], nums[endX][endY-i],   nums[startX+i][endY] =
			nums[endX-i][startY],   nums[endX][endY-i],   nums[startX+i][endY], nums[startX][startY+i]
		}
		startX,startY,endX,endY = startX+1,startY+1,endX-1,endY-1
	}
	print(nums)
}


/*
   00 01 02 03
   10 11 12 13
   20 21 22 23
   30 31 32 33

      tmp=00
      00=30
      30=33
      33=03
      03=tmp
*/

The function entry provided by leetcode, I replaced the parameter variable

func rotate(nums [][]int)  {
    
    
   startX ,startY, endX ,endY := 0,0,len(nums[0]) - 1, len(nums[0]) - 1
	for startX < endX {
    
    
		for i := 0; i < endX-startX; i++ {
    
    
			nums[startX][startY+i], nums[endX-i][startY], nums[endX][endY-i],   nums[startX+i]  [endY] =
			nums[endX-i][startY],   nums[endX][endY-i],   nums[startX+i][endY], nums[startX][startY+i]
		}
		startX,startY,endX,endY = startX+1,startY+1,endX-1,endY-1
	}
}

Full change map

Insert picture description here

Shuichi Shita

Insert picture description here

Guess you like

Origin blog.csdn.net/dawnto/article/details/113094675