摘要:题目要求也就是将递加的数字按照顺时针的顺序依次填入数组之中这道题目联系到,其实就相当好解决了。
题目要求
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
也就是将递加的数字按照顺时针的顺序依次填入数组之中
这道题目联系到Spiral Matrix I,其实就相当好解决了。Spiral Matrix I可以参考我的这篇博客
具体代码在参考完这篇博客后,就会发现,这里其实就是将读取数据反过来改为填入数据,代码如下:
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int rowStart = 0;
int rowEnd = n-1;
int colStart = 0;
int colEnd = n-1;
int number = 1;
while(rowStart<=rowEnd && colStart<=colEnd){
for(int i = colStart ; i<=colEnd ; i++){
result[rowStart][i] = number;
number++;
}
rowStart++;
for(int i = rowStart ; i<=rowEnd ; i++){
result[i][colEnd] = number;
number++;
}
colEnd--;
if(rowStart <= rowEnd){
for(int i = colEnd ; i>=colStart ; i--){
result[rowEnd][i] = number;
number++;
}
}
rowEnd--;
if(colStart<= colEnd){
for(int i = rowEnd ; i>= rowStart ; i--){
result[i][colStart] = number;
number++;
}
}
colStart++;
}
return result;
}
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/70150.html
摘要:代码添加该圈第一行添加最后一列添加最后一行添加第一列如果是奇数,加上中间那个点后续如果在中,给出的是和来代表行数和列数,该如何解决和的本质区别就是一个是任意长方形,一个是正方形,所以中不需要判断最后一行或者最后一列。 Spiral Matrix I Given a matrix of m x n elements (m rows, n columns), return all ele...
摘要:如果不在前两个循环之后的话,那么那多余的一行或一列就会被加入数组两次,造成错误的结果。解法和一样,只是简化了,甚至可以用一样的方法去做,只要把也换成。使用,以及最后讨论是否为奇数以判断中间是否有一个未循环的点,是这道题的两个有趣的地方。 Spiral Matrix I Problem Given a matrix of m x n elements (m rows, n columns...
摘要:复杂度思路注意循环条件。代码注意循环条件,要用而不是除以,因为精度准换问题只有一行或者一列的时候,就不要再继续搜索了 LeetCode[54] Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Fo...
摘要:螺旋矩阵给定一个包含个元素的矩阵行列,请按照顺时针螺旋顺序,返回矩阵中的所有元素。每次转向或都会自减。循环可操作性很高,可以直接操作索引坐标改变遍历方式,不再赘述。 54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix i...
摘要:螺旋矩阵给定一个包含个元素的矩阵行列,请按照顺时针螺旋顺序,返回矩阵中的所有元素。每次转向或都会自减。循环可操作性很高,可以直接操作索引坐标改变遍历方式,不再赘述。 54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix i...
阅读 1257·2021-11-24 09:39
阅读 1811·2021-11-18 13:18
阅读 2808·2021-11-15 11:38
阅读 2038·2021-09-26 09:47
阅读 1846·2021-09-22 15:09
阅读 1847·2021-09-03 10:29
阅读 1703·2019-08-29 17:28
阅读 3206·2019-08-29 16:30