Spiral Matrix II, Leetcode 解题笔记

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

数组实现题,注意边界情况。

public class Solution {
    public int[][] generateMatrix(int n) {
        
        int[][] matrix = new int[n][n];
        if(n == 0) return (new int[n][n]);
        //if(n == 1) return ;
        int row = 0;
        int col = 0;
        int row_end = n-1;
        int col_end = n-1;
        int cur = 1;
        
        int num = n*n;
        
        while(true){
            for(int i = col; i <= col_end; i++){
                matrix[row][i] = cur;
                cur++;
            }
            row++;
            if(cur > num) break;
            for(int j = row; j <= row_end; j++){
                matrix[j][col_end] = cur;
                cur++;
            }
            col_end--;
            if(cur > num) break;
            for(int i = col_end; i >= col; i--){
                matrix[row_end][i] = cur;
                cur++;
            }
            row_end--;
            if(cur > num) break;
            for(int j = row_end; j >= row; j--){
                matrix[j][col] = cur;
                cur++;
            }
            col++;
            if(cur > num) break;
        }
        return matrix;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s