【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); } };
相关文章推荐
- NOIP2012 普及组 T3 摆花——S.B.S.
- java.lang.String.indexOf()方法
- MySQL Connector ODBC 安装出现 “找不到指定的模块xxx”
- wps操作记录
- Nginx负载均衡配置实例详解
- Java/Android引用类型及其使用分析
- rpmbuild的一个小常识
- Axis2学习笔记:用户身份认证
- Android 自定义控件实现刮刮卡效果 真的就只是刮刮卡么
- iOS的几种后台机制
- 串行异步网络请求的简单实现
- java中BlockingQueue 的使用
- Oracle数据库语法之【DML】常用汇总-【更新】
- 数组中局部最小数的位置
- Linux和win7(win10)双系统时间错误问题 时间相差8小时
- ABP源码分析四十四:ZERO的配置
- MySql UDF 调用外部程序和系统命令
- listview gridview屏蔽滑动及嵌套时解决方法
- 托管项目到GitHub
- 在EntityFramework6中管理DbContext的正确方式——4DbContextScope:一个简单的,正确的并且灵活的管理DbContext实例的方式(外文翻译)