Leetcode刷题记——59. Spiral Matrix II(螺旋矩阵2)

来源:互联网 发布:nginx 如何装tomcat 编辑:程序博客网 时间:2024/05/22 05:04

一、题目叙述:

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

Subscribe to see which companies asked this question.

给定一个整数n,要求按螺旋的方式填充n*n二维数组。

二、解题思路:

Medium题,这题与54.螺旋矩阵思路基本一致,并且更加简单,思路参考http://blog.csdn.net/sunshine0_0/article/details/56678002

三、源码:

import java.util.ArrayList;  import java.util.Arrays;import java.util.List;    public class Solution  {   public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int times = n/2; int count = 1; int i,j,k,q,s; for (i = 0; i < times; i++) { for (j = i; j < n - i; j++) res[i][j] = count++; for (k = i + 1; k < n - i; k++) res[k][j - 1] = count++; for (q = j - 2; q >= i; q--)                   res[k-1][q] = count++;               for (s = k - 2; s > i; s--)                   res[s][i] = count++;   } n = n - times * 2; if (n != 0) res[times][times] = count; return res;      }    public static void main(String args[])          {                          //  int[] digits = {0};              Solution solution = new Solution();            //  int[][] abc = {{2,5},{8,4}};        //  int[] b = {2,3,4};         // for(int i = 0; i < abc.length; i ++)                        System.out.print(Arrays.deepToString(solution.generateMatrix(0)));                    }      }  


0 0
原创粉丝点击