码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Spiral Matrix II

时间:2015-12-27 13:22:30      阅读:111      评论: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 ]
]

思路:

这题比I更容易,因为是完全的正方形

package array;

public class SpiralMatrixII {

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = i; j < n -i; ++j) {
                matrix[i][j] = ++num;
            }
            for (int j = i + 1; j < n -i; ++j) {
                matrix[j][n - i - 1] = ++num;
            }
            for (int j = n - i - 2; j >= i; --j) {
                matrix[n - i - 1][j] = ++num;
            }
            for (int j = n - i - 2; j >= i + 1; --j) {
                matrix[j][i] = ++num;
            }
        }
        
        return matrix;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SpiralMatrixII s = new SpiralMatrixII();
        int n = 1;
        int[][] matrix = s.generateMatrix(n);
        for (int i = 0; i < n; ++i) {            
            for (int j = 0; j < n; ++j) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

}

 

LeetCode - Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5079867.html

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