网站建设哪家好服务,邯郸网络技术公司,公司门户网站是什么,在线考试系统网站模板题目 思路
对于每层#xff0c;从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于 (top,left)#xff0c;右下角位于 (bottom,right)#xff0c;按照如下顺序填入当前层的元素。 从左到右填入上侧元素#xff0c;依次为 (top,left) 到 (top,right)。 从上到…题目 思路
对于每层从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于 (top,left)右下角位于 (bottom,right)按照如下顺序填入当前层的元素。 从左到右填入上侧元素依次为 (top,left) 到 (top,right)。 从上到下填入右侧元素依次为 (top1,right) 到 (bottom,right)。 如果 leftright 且 topbottom则从右到左填入下侧元素依次为 (bottom,right−1) 到 (bottom,left1)以及从下到上填入左侧元素依次为 (bottom,left) 到 (top1,left)。
填完当前层的元素之后将 left 和 top 分别增加 1将 right 和 bottom 分别减少 1进入下一层继续填入元素直到填完所有元素为止。
代码
class Solution {
public:vectorvectorint generateMatrix(int n) {int num 1;vectorvectorint matrix(n, vectorint(n));int left 0, right n - 1, top 0, bottom n - 1;while (left right top bottom) {for (int column left; column right; column) //列是从左边开始向右移动{matrix[top][column] num; //给矩阵赋值num; //矩阵值增加}for (int row top 1; row bottom; row) { //行从第一行开始向下增加matrix[row][right] num; //继续增加给矩阵赋值num;}if (left right top bottom) {for (int column right - 1; column left; column--) {matrix[bottom][column] num;num;}for (int row bottom; row top; row--) {matrix[row][left] num;num;}}left;right--;top;bottom--;}return matrix;}
};