【Leetcode】Spiral Matrix II

来源:互联网 发布:sql server 2008下载 编辑:程序博客网 时间:2024/06/06 11:47

题目链接:https://leetcode.com/problems/spiral-matrix-ii/

题目:

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

思路:

1、由外向内一圈一圈的计算,首先计算有几圈,用dim表示,根据dim控制循环次,复杂的地方在于判断每圈每段的起始位置。这种方法思路简单,实现麻烦。

2、用递归实现,参考 http://fisherlei.blogspot.com/2013/04/leetcode-spiral-matrix-ii-solution.html   看起来也挺费劲的。

算法1:

public int[][] generateMatrix(int n) {int matrix[][] = new int[n][n];int dim = n / 2;if (n % 2 != 0)dim++;int s = 1;for (int i = 0; i < dim; i++) {for (int j = i; j < n - i; j++) {//上matrix[i][j] = s;s++;}for (int x = i + 1; x < n - i; x++) {//右matrix[x][n - i - 1] = s;s++;}for (int x = n - 2 - i; x >= i; x--) {//下matrix[n - 1 - i][x] = s;s++;}for (int x = n - 2 - i; x > i; x--) {//左matrix[x][i] = s;s++;}}return matrix;}




0 0
原创粉丝点击