《leetcode》spiral-matrix-ii(构造螺旋矩阵)
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》spiral-matrix-ii(构造螺旋矩阵)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解析:螺旋矩陣算是數組中比較經典的問題了。如何構造螺旋矩陣返回呢?我們可以把該數組看成是構造上方、右方、下方、左方來構造。注意:每構造一個上、右、下、左就把循環數+1,就像剝洋蔥一樣,搞完一層就少一層。
public class Solution {public int[][] generateMatrix(int n) {int [][] arr = new int[n][n];int count=0;//構造的數int x=0;int y=0;int num=1;int cycle=0;//控制循環的層數while (count!=(n*n)){while (y<(n-cycle)&&(count!=(n*n))){//上方arr[x][y]=num++;y++;count++;}y--;x++;while (x<n-cycle&&(count!=(n*n))){//右方arr[x][y]=num++;x++;count++;}x--;y--;while (y>=cycle&&(count!=(n*n))){//下方arr[x][y]=num++;y--;count++;}y++;x--;while (x>cycle&&(count!=(n*n))){//左側arr[x][y]=num++;x--;count++;}x++;y++;cycle++;//完成一圈循環數+1,下次內圈變小}return arr;} }總結
以上是生活随笔為你收集整理的《leetcode》spiral-matrix-ii(构造螺旋矩阵)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《编程题》来自某游戏公司
- 下一篇: 《编程题》找出数组中出现次数超过一半的数