Spiral Matrix II
Given an integern, generate a square matrix filled with elements from 1 ton2in spiral order.
For example,
Givenn=3
,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
有前面的Spiral Matrix作为基础就好做这道题了。
关键就是处理下标,要学会如何去跟踪下标,这个思维能力也需要锻炼。
锻炼好,那么就不需要20分钟就可以写出下面那么简练的程序了。
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
int i = 0, j = n-1;
vector<vector<int> > res(n, vector<int>(n));
int num = 1;
for (; i < j; i++, j--)
{
for (int k = i; k <= j; k++)
{
res[i][k] = num;
num++;
}
for (int k = i+1; k < j; k++)
{
res[k][j] = num;
num++;
}
for (int k = j; k >= i; k--)
{
res[j][k] = num;
num++;
}
for (int k = j-1; k > i; k--)
{
res[k][i] = num;
num++;
}
}
//n为基数,剩下一个空格的时候,不能重复填了。额外处理。
if (i == j) res[i][j] = num;
return res;
}
};
测试程序:
int main()
{
Solution solu;
vector<vector<int> > v = solu.generateMatrix(10);
for (auto x:v)
{
for (auto y:x)
cout<<y<<"\t";
cout<<endl;
}
system("pause");
return 0;
}
漂亮的打印结果:
//2014-1-29 update
vector<vector<int> > generateMatrix(int n)
{
vector<vector<int> > rs(n, vector<int>(n));
int c = 1, i = 0;
for (n--; i < n; i++, n--)
{
for (int j = i; j < n; j++, c++)
rs[i][j] = c;
for (int j = i; j < n; j++, c++)
rs[j][n] = c;
for (int j = n; j > i ; j--, c++)
rs[n][j] = c;
for (int j = n; j > i ; j--, c++)
rs[j][i] = c;
}
if (i == n) rs[i][i] = c;
return rs;
}
分享到:
相关推荐
Swif-LeetCode-Utils:在LeetCode上快速创建和打印ListNode和TreeNode的方式
462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/...
刷LeetCode刷LeetCode刷LeetCode刷LeetCode刷LeetCode
leetcode 分类 LeetCode Notes of LeetCode exercise 前期题目适用python刷的,后来改用了java 题目分类:
Leetcode 138. 复制带随机指针的链表问题描述138. 复制带随机指针的链表 - 力扣(LeetCode)算法解法1:hashtab解法1: 实现解法
leetcode中文版
leetcode卡leetcode_practices_learncard_recursionii 我的 leetcode 递归练习 ii 学习卡在 100% 完成 :) 我的 Java8 备忘单:
vs code LeetCode 插件
Java算法刷题带注释Leetcode,基础算法
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
大佬的leetcode刷题笔记(c++版本)
100个leetCode详细解答
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101_源码.zip
LeetCode 刷题汇总1
LeetCode 选讲1
leetcode三角形打印 LeetCode-classify 用于归类总结其中的一类题型 剑指Offer 3. 数组中重复的数字 4. 二维数组中的查找 5. 替换空格 6. 从尾到头打印链表 7. 重建二叉树(前、中;前、后;中、后) 9.二个栈实现...
126.Word_Ladder_II_词语阶梯二【LeetCode单题讲解系列】
leetcode category other hot keywords:Palindrome(mic), Subsequence Array 螺旋矩阵Spiral Matrix 顺时针打印矩阵 Next Permutation Product of Array Except Self 189.rotate-array 283.move-zero Range Sum ...