leetcode 81: Spiral Matrix II

Spiral Matrix II Mar 28 '12

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) {
        // Start typing your Java solution below
        // DO NOT write main() function        
        int[][] res = new int[n][n];
        if(n<1) return res;
        
        int top=0, bottom=n-1, left=0, right=n-1;
        
        int loop = (n+1)/2;
        
        for(int i=0, seq=1; ibottom) return res;
            for(int j=top; j<=bottom; j++) {
                res[j][right] = seq++;
            }
            right--;
            
            if(left>right) return res;
            for(int j=right; j>=left; j--) {
                res[bottom][j] = seq++;
            }
            bottom--;
            
            if(top>bottom) return res;
            for(int j=bottom; j>=top; j--) {
                res[j][left] = seq++;
            }
            left++;
        }
        
        return res;
    }
}


 

转载于:https://www.cnblogs.com/xishibean/archive/2013/02/18/2951307.html

你可能感兴趣的:(leetcode 81: Spiral Matrix II)