Leetcode59. Spiral Matrix II

来源:互联网 发布:java api1.7中文版 编辑:程序博客网 时间:2024/05/16 08:09

59. Spiral Matrix II

1、原题

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 ]]

2、题意解析与思路

题目意思很简单,就是给我们一个正数n,让我们按照螺旋顺序将1-n^2这些数填充到二维数组当中,题目给了一个样例,就是左->右,上->下,右->左,下->上的这个顺序。
我做这道题的算法比较无脑,就是按照上面说的顺序进行数字的填充。具体请看代码。

3、代码

public int[][] generateMatrix(int n) {int[][] res = new int[n][n];//定义4个标志,用来进行多次螺旋顺序的操作int left = 0, top = 0;int right = n, down = n;//填充数字int count = 1;while (left < right) {//从左到右,然后top标志加1for (int i = left; i < right; i++) {res[top][i] = count++;}top++;//从上到下,然后right标志减1for (int i = top; i < down; i++) {res[i][right-1] = count++;}right--;//从右到左,然后down标志减1for (int i = right - 1; i >= left; i--) {res[down-1][i] = count++;}down--;//从下到上,然后left标志加1for (int i = down - 1; i >= top; i--) {res[i][left] = count++;}left++;}return res;    }


原创粉丝点击