#yyds干货盘点# leetcode算法题:螺旋矩阵 II

网友投稿 480 2022-10-29

#yyds干货盘点# leetcode算法题:螺旋矩阵 II

#yyds干货盘点# leetcode算法题:螺旋矩阵 II

题目:

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:

输入:n = 3

输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1

输出:[[1]]

代码实现:

class Solution { public int[][] generateMatrix(int n) { int num = 1; int[][] matrix = new int[n][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; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Razorframe – 用于大规模授权实时应用程序的一个Node.js模块
下一篇:基于python35,使用基于Linux的任务命令,CNIC自动打卡程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~