Spiral Matrix II

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[][] ret = new int[n][n]; 
        if ( n == 0) {
            return ret; 
        }
        int top = 0;
        int bottom = n - 1;
        int left = 0; 
        int right = n - 1; 
        int num = 1; 
        while (top <= bottom) {
            
            if (top == bottom) {
                ret[top][top] = num++; 
                break; 
            }
            //first line
            for (int i = left; i < right; i++) {
                ret[top][i] = num++; 
            }
            //right line
            for (int i = top; i < bottom; i++) {
                ret[i][right] = num++; 
            }
            //bottom line 
            for (int i = right; i > left; i--) {
                ret[bottom][i] = num++; 
            }
            //left line 
            for (int i = bottom; i > top; i--) {
                ret[i][left] = num++; 
            }
            top++; 
            bottom--; 
            left++; 
            right--; 
        }
        return ret; 
    }
}
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