59. Spiral Matrix II
2016-05-11 14:58
309 查看
题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:
题意:
给定一个整数n,生成n*n形螺旋数组,如上所示。
转载链接:https://leetcode.com/discuss/21677/simple-c-solution-with-explaination
思路:
按照规律上右下左的顺序依次填充数字。
代码:
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 ] ]
题意:
给定一个整数n,生成n*n形螺旋数组,如上所示。
转载链接:https://leetcode.com/discuss/21677/simple-c-solution-with-explaination
思路:
按照规律上右下左的顺序依次填充数字。
代码:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int> > ret( n, vector<int>(n) ); int k = 1, i = 0; while( k <= n * n ) { int j = i; // four steps while( j < n - i ) // 1. horizonal, left to right ret[i][j++] = k++; j = i + 1; while( j < n - i ) // 2. vertical, top to bottom ret[j++][n-i-1] = k++; j = n - i - 2; while( j > i ) // 3. horizonal, right to left ret[n-i-1][j--] = k++; j = n - i - 1; while( j > i ) // 4. vertical, bottom to top ret[j--][i] = k++; i++; // next loop } return ret; } };
相关文章推荐
- 用C++进行简单的文件I/O操作
- Android测试环境搭建(win7)
- (礼拜三log)前端开发,form标签的使用,jsp param标签的使用,${param}
- CDISC SDTM AE domain学习笔记 - 1
- 职员有薪水了
- 职员有薪水了
- jstl中的format标签
- Android Activity的生命周期分析
- 粒子、地图
- 算法:替换字符串中的空格
- 六款数据挖掘工具
- [转]ping检测网络连接异常
- 系统升级成win10 后,eclipse的图片打开后成了乱码
- Bootstrap Datetimepicker 年月日时分秒控件
- Java 如果阻止二次继承
- 事件
- (5)Redis封装类
- angular 鼠标移入移开元素显示或隐藏
- Vijos1404 遭遇战 最短路,dijkstra,堆
- 网络HTTP请求状态详解