螺旋矩阵

http://www.lintcode.com/zh-cn/problem/spiral-array/

public class Solution {
    /**
     * @param n: a Integer
     * @return: a spiral array
     */
    public int[][] spiralArray(int n) {
        // write your code here
        if (n <= 0) {
            return null;
        }
//       要开始的上边界
        int top = 0;
//       要开始的左边界
        int left = 0;
//       要开始的右边界
        int right = n - 1;
//       要开始的下边界
        int bottom = n - 1;
        int index = 1;
        int[][] res = new int[n][n];
        while (true) {
            for (int i = left; i <= right; i++) {
                res[top][i] = index;
                index++;
            }
            top++;
            if (top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                res[i][right] = index;
                index++;
            }
            right--;
            if (left > right) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res[bottom][i] = index;
                index++;
            }
            bottom--;
            if (top > bottom) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                res[i][left] = index;
                index++;
            }
            left++;
            if (left > right) {
                break;
            }
        }
        return res;
    }
}

你可能感兴趣的:(螺旋矩阵)