美文网首页
13、Rotate Image

13、Rotate Image

作者: 一念之见 | 来源:发表于2016-08-05 15:11 被阅读13次

![Uploading 屏幕快照 2016-08-05 11.28.09_715873.png . . .]##Problem Description
You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

Analyze

Code

class Solution {
    func rotate(inout matrix: [[Int]]) {
        let lines = matrix.count
        
        func swapInMatrix(left: (Int, Int), right: (Int, Int)) {
            let temp = matrix[left.0][left.1]
            matrix[left.0][left.1] = matrix[right.0][right.1]
            matrix[right.0][right.1] = temp
        }
      
        for line in 0..<lines {
            for column in 0..<lines-line {
                swapInMatrix((line, column), right: (lines-1-column, lines-1-line))
            }
        }
        
        for line in 0..<lines/2 {
            for column in 0..<lines {
                swapInMatrix((line, column), right: (lines-1-line, column))
            }
        }
    }
}

相关文章

网友评论

      本文标题:13、Rotate Image

      本文链接:https://www.haomeiwen.com/subject/ocphsttx.html