您的位置:首页 > 其它

【Leetcode】之 Spiral Matrix

2016-05-06 13:36 411 查看

一.问题描述

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]
.

二.我的解题思路

这道题是今年腾讯实习生招聘的笔试题。解题思路其实蛮简单的,就是使用分治递归的算法思想,先打印出最外层的数字,然后再递归求解内层的。需要注意的是特殊情况的处理,比如当前层如果只有一行或者一列,那么就需要额外注意。测试通过的程序如下:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int row_len = matrix.size();
if(row_len==0) return res;
int line_len = matrix[0].size();
gen_res(matrix,0,row_len-1,0,line_len-1,res);
return res;
}

void gen_res(vector<vector<int>>& matrix,int row_st,int row_end,int line_st,int line_end,vector<int> &res){
if(row_st>row_end || line_st>line_end) return;
for(int i=line_st;i<=line_end;i++)
res.push_back(matrix[row_st][i]);
for(int i=row_st+1;i<=row_end;i++)
res.push_back(matrix[i][line_end]);
if((row_end!=row_st) && (line_st!=line_end)){
for(int i=line_end-1;i>line_st;i--)
res.push_back(matrix[row_end][i]);
for(int i=row_end;i>row_st;i--)
res.push_back(matrix[i][line_st]);
}

row_st++;line_st++;
row_end--;line_end--;
gen_res(matrix,row_st,row_end,line_st,line_end,res);

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: