题目
给出一个二维数组, 让二维数组顺时针螺旋输出.
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]
思路1
计算拐点, 确定方向. 但是计算比较复杂, 顺序是顺时针, 因此方向是有规律的, 只要找出拐点, 就可以确定方向.
不同规模的数组拐点判断不一样.
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int m = matrix.size();
if (m == 0) {
return result;
}
int n = matrix[0].size();
if (n == 0){
result = matrix[0];
return result;
}
int direction = 0,count = 1;
int row = 0, col = 0;
int maxRow = m - 1;
int maxCol = n - 1;
int minRow = 0;
int minCol = 0;
result.push_back(matrix[row][col]);
while(count < m * n) {
if (direction == 0 && col == maxCol) {
minRow++;
direction++;
}else if (direction == 1 && row == maxRow) {
maxCol--;
direction++;
}else if (direction == 2 && col == minCol) {
maxRow--;
direction++;
}else if (direction == 3 && row == minRow) {
minCol++;
direction++;
}
direction = direction % 4;
switch (direction)
{
case 0:
col++;
break;
case 1:
row++;
break;
case 2:
col--;
break;
case 3:
row--;
break;
default:
break;
}
result.push_back(matrix[row][col]);
count ++;
}
return result;
}
总结
考虑边界, 确保index不会出现负数, 应该使用unsigned
防止负数.
网友评论