当前位置:网站首页>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;}}边栏推荐
猜你喜欢
随机推荐
【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
【STM32】标准库-自定义BootLoader
转运RNA(tRNA)甲基化修饰7-甲基胞嘧啶(m7C)|tRNA-m7G
Use ControlTemplate or Style from resource file in WPF .cs and find the control
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
JMeter笔记5 |Badboy使用和录制
力扣59-螺旋矩阵 II——边界判断
Auto.js实现朋友圈自动点赞
ES6简介及let、var、const区别
汉源高科8光口12电口交换机千兆8光8电12电16电网管型工业以太网交换机
LeetCode 1374. 生成每种字符都是奇数个的字符串
Anaconda virtual environment migration
力扣707-设计链表——链表
leetcode 剑指 Offer 58 - II. 左旋转字符串
李沐动手学深度学习V2-BERT微调和代码实现
Node version switching tool NVM and npm source manager nrm
LeetCode 899. 有序队列
面试官:为什么 0.1 + 0.2 == 0.300000004?
List类的超详细解析!(超2w+字)
若依集成easyexcel实现excel表格增强









