《leetcode》spiral-matrix-ii(构造螺旋矩阵)
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》spiral-matrix-ii(构造螺旋矩阵)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
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 ]
]
解析:螺旋矩陣算是數(shù)組中比較經(jīng)典的問題了。如何構(gòu)造螺旋矩陣返回呢?我們可以把該數(shù)組看成是構(gòu)造上方、右方、下方、左方來構(gòu)造。注意:每構(gòu)造一個(gè)上、右、下、左就把循環(huán)數(shù)+1,就像剝洋蔥一樣,搞完一層就少一層。
public class Solution {public int[][] generateMatrix(int n) {int [][] arr = new int[n][n];int count=0;//構(gòu)造的數(shù)int x=0;int y=0;int num=1;int cycle=0;//控制循環(huán)的層數(shù)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))){//左側(cè)arr[x][y]=num++;x--;count++;}x++;y++;cycle++;//完成一圈循環(huán)數(shù)+1,下次內(nèi)圈變小}return arr;} }總結(jié)
以上是生活随笔為你收集整理的《leetcode》spiral-matrix-ii(构造螺旋矩阵)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《编程题》来自某游戏公司
- 下一篇: 《编程题》找出数组中出现次数超过一半的数