码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 59 Spiral Matrix II ------ java

时间:2016-08-26 15:03:20      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

 这道题其实就是第54题Spiral Matrix的输入和输出反过来而已。

很简单,一圈一圈往里写数据,circle 共有n/2+1圈。然后写入数据即可。

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][]    result = new int[n][n];
        int num = n/2+1;
        int left = 0,right = n-1;
        int ans = 1;
        for ( int circle = 0;circle < num;circle++){
            for( int i = left;i<=right;i++){
                result[circle][i] = ans;
                ans++;
            }
            for( int i = left+1;i<=right;i++){
                result[i][n-1-circle] = ans;
                ans++;
            }
            for( int i =right-1;i>=left;i--){
                result[n-circle-1][i] = ans;
                ans++;
            }
            for( int i = right-1;i>left;i--){
                result[i][circle] = ans;
                ans++;
            }
            left++;
            right--;
        }
     
        return result;
    }
}

 

 

 

leetcode 59 Spiral Matrix II ------ java

标签:

原文地址:http://www.cnblogs.com/xiaoba1203/p/5810127.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!