LeetCode-59-Spiral Matrix II
Posted 无名路人甲
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-59-Spiral Matrix II相关的知识,希望对你有一定的参考价值。
算法描述:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解题思路:模拟,注意边界。
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> results(n,vector<int>(n,0)); int rowBegin = 0; int rowEnd = n-1; int colBegin = 0; int colEnd = n-1; int index = 1; while(rowBegin <= rowEnd && colBegin <=colEnd){ for(int i=colBegin; i <= colEnd; i++) results[rowBegin][i] = index++; rowBegin++; for(int i=rowBegin; i <= rowEnd; i++) results[i][colEnd] = index++; colEnd--; if(rowBegin <= rowEnd && colBegin <= colEnd){ for(int i=colEnd; i >= colBegin; i--) results[rowEnd][i] = index++; rowEnd--; for(int i=rowEnd; i >= rowBegin; i--) results[i][colBegin] = index++; colBegin++; } } return results; }
以上是关于LeetCode-59-Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]59. Spiral Matrix II