[Leetcode] Spiral Matrix 螺旋矩陣

Spiral Matrix I

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.python

For example, Given the following matrix:app

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].code

順序添加法

複雜度

時間 O(NM) 空間 O(1)element

思路

首先考慮最簡單的狀況,如圖咱們先找最外面這圈X,這種狀況下咱們是第一行找前4個,最後一列找前4個,最後一行找後4個,第一列找後4個,這裏咱們能夠發現,第一行和最後一行,第一列和最後一列都是有對應關係的。即對i行,其對應行是m - i - 1,對於第j列,其對應的最後一列是n - j - 1it

XXXXX
XOOOX
XOOOX
XOOOX
XXXXX

而後進入到裏面那一圈,一樣的順序沒什麼問題,然而關鍵在於下圖這麼兩種狀況,一圈已經沒有四條邊了,因此咱們要單獨處理,只加那惟一的一行或一列。另外,根據下圖咱們能夠發現,圈數是寬和高中較小的那個,加1再除以2。io

OOOOO  OOO
OXXXO  OXO
OOOOO  OXO
       OXO
       OOO

代碼

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList<Integer>();
        if(matrix.length == 0) return res;
        int m = matrix.length, n = matrix[0].length;
        // 計算圈數
        int lvl = (Math.min(m, n) + 1) / 2;
        for(int i = 0; i < lvl; i++){
            // 計算相對應的該圈最後一行
            int lastRow = m - i - 1;
            // 計算相對應的該圈最後一列
            int lastCol = n - i - 1;
            // 若是該圈第一行就是最後一行,說明只剩下一行
            if(i == lastRow){
                for(int j = i; j <= lastCol; j++){
                    res.add(matrix[i][j]);
                }
            // 若是該圈第一列就是最後一列,說明只剩下一列
            } else if(i == lastCol){
                for(int j = i; j <= lastRow; j++){
                    res.add(matrix[j][i]);
                }
            } else {
                // 第一行
                for(int j = i; j < lastCol; j++){
                    res.add(matrix[i][j]);
                }
                // 最後一列
                for(int j = i; j < lastRow; j++){
                    res.add(matrix[j][lastCol]);
                }
                // 最後一行
                for(int j = lastCol; j > i; j--){
                    res.add(matrix[lastRow][j]);
                }
                // 第一列
                for(int j = lastRow; j > i; j--){
                    res.add(matrix[j][i]);
                }
            }
        }
        return res;
    }
}

2018/2ast

class Solution:
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if (matrix is None or len(matrix) == 0):
            return []
        rows = len(matrix)
        cols = len(matrix[0])
        level = (min(rows, cols) + 1) // 2
        result = []
        for currLevel in range(0, level):
            firstRow = currLevel
            firstCol = currLevel
            lastRow = rows - currLevel - 1
            lastCol = cols - currLevel - 1
            if firstRow == lastRow:
                for col in range(firstCol, lastCol + 1):
                    result.append(matrix[firstRow][col])
                return result
            if firstCol == lastCol:
                for row in range(firstRow, lastRow + 1):
                    result.append(matrix[row][firstRow])
                return result
            for col in range(firstCol, lastCol):
                result.append(matrix[firstRow][col])
            for row in range(firstRow, lastRow):
                result.append(matrix[row][lastCol])
            for col in range(lastCol, firstCol, -1):
                result.append(matrix[lastRow][col])
            for row in range(lastRow, firstRow, -1):
                result.append(matrix[row][firstCol])
        return result

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.class

For example, Given n = 3,變量

You should return the following matrix:List

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

順序添加法

複雜度

時間 O(NM) 空間 O(1)

思路

本題就是按照螺旋的順序把數字依次塞進去,咱們能夠維護上下左右邊界的四個變量,一圈一圈往裏面添加。最後要注意的是,若是n是奇數,要把中心那個點算上。

代碼

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int left = 0, right = n - 1, bottom = n - 1, top = 0, num = 1;
        while(left < right && top < bottom){
            // 添加該圈第一行
            for(int i = left; i < right; i++){
                res[top][i] = num++;
            }
            // 添加最後一列
            for(int i = top; i < bottom; i++){
                res[i][right] = num++;
            }
            // 添加最後一行
            for(int i = right; i > left; i--){
                res[bottom][i] = num++;
            }
            // 添加第一列
            for(int i = bottom; i > top; i--){
                res[i][left] = num++;
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        // 若是是奇數,加上中間那個點
        if(n % 2 == 1){
            res[n / 2][n / 2] = num;
        }
        return res;
    }
}

2018/2

class Solution:
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 0:
            return []
        matrix = [[0 for i in range(0, n)] for j in range(0, n)]
        left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1
        while left < right and top < bottom:
            for col in range(left, right):
                matrix[top][col] = num
                num += 1
            for row in range(top, bottom):
                matrix[row][right] = num
                num += 1
            for col in range(right, left, -1):
                matrix[bottom][col] = num
                num += 1
            for row in range(bottom, top, -1):
                matrix[row][left] = num
                num += 1
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        if n % 2 != 0:
            matrix[left][top] = num
        return matrix

後續 Follow Up

  1. 若是在matrix ii中,給出的是m和n來表明行數和列數,該如何解決?

i和ii的本質區別就是一個是任意長方形,一個是正方形,因此ii中不須要判斷最後一行或者最後一列。既然沒有了正方形的前提,那生成矩陣的方法就和i是同樣的了。

class Solution:
    def generateMatrix(self, m, n):
        # m rows, n cols
        if m == 0 or n == 0:
            return []
        matrix = [[0 for i in range(0, n)] for j in range(0, m)]
        num = 1
        level = (min(m, n) + 1) // 2
        for currLevel in range(0, level):
            lastRow = m - currLevel - 1
            lastCol = n - currLevel - 1
            firstRow = currLevel
            firstCol = currLevel
            if firstRow == lastRow:
                for col in range(firstCol, lastCol + 1):
                    matrix[firstRow][col] = num
                    num += 1
                return matrix
            if firstCol == lastCol:
                for row in range(firstRow, lastRow + 1):
                    matrix[row][firstRow] = num
                    num += 1
                return matrix
            for col in range(firstCol, lastCol):
                matrix[firstRow][col] = num
                num += 1
            for row in range(firstRow, lastRow):
                matrix[row][lastCol] = num
                num += 1
            for col in range(lastCol, firstCol, -1):
                matrix[lastRow][col] = num
                num += 1
            for row in range(lastRow, firstRow, -1):
                matrix[row][firstCol] = num
                num += 1
        return matrix
相關文章
相關標籤/搜索