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

一、题目叙述:

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)));      
          
    }      
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值