Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
給一m*n大小的矩陣(m個直排、n個橫排),按照螺旋順序回傳裡面的元素。
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
vector
因此變成空的,要將他從矩陣中移除。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
for(int dir=0;matrix.size()!=0;dir++)
{
for(int i=matrix.size()-1;i>=0;i--)
{
if(matrix[i].size()==0)
matrix.pop_back();
}
if(matrix.size()==0) break;
if(dir%4==0)
{
for(int i=0;i<matrix[0].size();i++)
{
ans.push_back(matrix[0][i]);
}
matrix.erase(matrix.begin());
}
else if(dir%4==1)
{
for(int i=0;i<matrix.size();i++)
{
ans.push_back(matrix[i].back());
matrix[i].pop_back();
}
}
else if(dir%4==2)
{
for(int i=matrix.back().size()-1;i>=0;i--)
{
ans.push_back(matrix.back()[i]);
}
matrix.pop_back();
}
else
{
for(int i=matrix.size()-1;i>=0;i--)
{
ans.push_back(matrix[i][0]);
matrix[i].erase(matrix[i].begin());
}
}
}
return ans;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up