当前位置:网站首页>Likou 59 - Spiral Matrix II - Boundary Judgment
Likou 59 - Spiral Matrix II - Boundary Judgment
2022-08-03 20:11:00 【Zhang Dui Dui)】
Title description
Given you a positive integer n
, generate a 1
to n2
all elements, and the elements are spirally arranged in clockwise order n x n
Square matrix matrix
.
Solution ideas
- We can create a new n*n empty matrix and add data to it according to the requirements of the title;
- Define the upper, lower, left, and right boundaries of the matrix as t , b , l , r ;
- The new num is initialized to 1 and incremented by 1 after each addition;
- Take a 3*3 matrix as an example: First, you need to fill the first row with 1,2,3 from left to right, so the loop condition at this time should be:
for(int i = l; i <= r; i++) arr[t][i] = num++; t++;
- The purpose of t++ is to move the upper bound (the blue line) down to shrink the matrix;
- Next need to add 4,5, the loop condition is:
for(int i = t; i <= b; i++) arr[i][r] = num++; r--;
- The green right border line moves to the left, and then fills 6,7, the loop condition is:
for(int i = r; i >= l; i--) arr[b][i] = num++; b--;
- The lower border line (red line) moves up, and then fills element 8, the loop condition is:
for(int i = b; i >= t; i--) arr[i][l] = num++; l++;
- The left border line (yellow line) moves to the right, so far the cycle is over, and the outermost layer of elements has been filled;
- If the cycle is not finished, it will continue to repeat the above four steps and continuously adjust the four boundary lines;
- The condition for judging whether the loop is completed is num <= target. If num does not exceed target, it means that the element has not been filled.
Input and output example
Code
class Solution {public int[][] generateMatrix(int n) {int num = 1, target = n*n;int l = 0, r = n-1, t = 0, b = n-1;int[][] arr = new int[n][n];while(num <= target){for(int i = l; i <= r; i++) arr[t][i] = num++;t++;for(int i = t; i <= b; i++) arr[i][r] = num++;r--;for(int i = r; i >= l; i--) arr[b][i] = num++;b--;for(int i = b; i >= t; i--) arr[i][l] = num++;l++;}return arr;}}
边栏推荐
猜你喜欢
随机推荐
多模态 参考资料汇总
软件测试基本流程有哪些?权威的第三方软件检测机构推荐
CLIP论文解读
一种能有效缓解环境噪声对音频质量干扰的方案
C51 存储类型与存储模式
【HiFlow】经常忘记签到怎么办?使用腾讯云场景连接器每天提醒你。
Detailed explanation of JWT
RNA核糖核酸修饰RNA-HiLyte FluorTM 405荧光染料|RNA-HiLyte FluorTM 405
力扣203-移除链表元素——链表
若依集成browscap读取浏览器用户代理
李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
抖音web逆向教程
ThreadLocal详解
头条服务端一面经典10道面试题解析
华为设备配置VRRP负载分担
ESP8266-Arduino编程实例-MCP4725数模转换器驱动
LeetCode 1374. 生成每种字符都是奇数个的字符串
为什么 BI 软件都搞不定关联分析
PHP according to the longitude and latitude calculated distance two points
Anaconda virtual environment migration