Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
?
打印螺旋矩陣
逐個環的打印, 對于m *n的矩陣,環的個數是 (min(n,m)+1) / 2。對于每個環順時針打印四條邊。
注意的是:最后一個環可能只包含一行或者一列數據
class Solution {
public:vector<int> spiralOrder(vector<vector<int> > &matrix) {int m = matrix.size(), n;if(m != 0)n = matrix[0].size();int cycle = m > n ? (n+1)/2 : (m+1)/2;//環的數目vector<int>res;int a = n, b = m;//a,b分別為當前環的寬度、高度for(int i = 0; i < cycle; i++, a -= 2, b -= 2){//每個環的左上角起點是matrix[i][i],下面順時針依次打印環的四條邊for(int column = i; column < i+a; column++)res.push_back(matrix[i][column]);for(int row = i+1; row < i+b; row++)res.push_back(matrix[row][i+a-1]);if(a == 1 || b == 1)break; //最后一個環只有一行或者一列for(int column = i+a-2; column >= i; column--)res.push_back(matrix[i+b-1][column]);for(int row = i+b-2; row > i; row--)res.push_back(matrix[row][i]);}return res;}
};
?
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ] ]
本質上和上一題是一樣的,這里我們要用數字螺旋的去填充矩陣。同理,我們也是逐個環的填充,每個環順時針逐條邊填充???????????????? 本文地址
class Solution {
public:vector<vector<int> > generateMatrix(int n) {vector<vector<int> > matrix(n, vector<int>(n));int a = n;//a為當前環的邊長int val = 1;for(int i = 0; i < n/2; i++, a -= 2){//每個環的左上角起點是matrix[i][i],下面順時針依次填充環的四條邊for(int column = i; column < i+a; column++)matrix[i][column] = val++;for(int row = i+1; row < i+a; row++)matrix[row][i+a-1] = val++;for(int column = i+a-2; column >= i; column--)matrix[i+a-1][column] = val++;for(int row = i+a-2; row > i; row--)matrix[row][i] = val++;}if(n % 2)matrix[n/2][n/2] = val;//n是奇數時,最后一個環只有一個數字return matrix;}
};
?
【版權聲明】轉載請注明出處:http://www.cnblogs.com/TenosDoIt/p/3774747.html