2014年2月21日星期五

LeetCode - 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) {
        if(n<0) {
            return null;
        }
        int matrix[][] = new int[n][n];
        if(n==0) {
            return matrix;
        }
        int t = 1;
        int loop = 0;
        while(t<=n*n) {
            for(int i=loop;i<n-loop;i++) {
                matrix[loop][i] = t++;
            }
            if(t>n*n) {
                break;
            }
            for(int i=loop+1;i<n-loop-1;i++) {
                matrix[i][n-loop-1] = t++;
            }
            if(t>n*n) {
                break;
            }
            for(int i=n-loop-1;i>=loop;i--) {
                matrix[n-loop-1][i] = t++;
            }
            if(t>n*n) {
                break;
            }
            for(int i=n-loop-2;i>loop;i--) {
                matrix[i][loop] = t++;
            }
            loop++;
        }
        return matrix;
    }
}

============

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n <= 0) {
            return res;
        }
        int val = 1;
        int max = n * n;
        int direction = 0;
        int i = 0;
        int j = -1;
        while (val <= max) {
            int i2 = i;
            int j2 = j;
            if (direction == 0) {
                j2 += 1;
            } else if (direction == 1) {
                i2 += 1;
            } else if (direction == 2) {
                j2 -= 1;
            } else if (direction == 3) {
                i2 -= 1;
            }
            if (i2 < 0 || i2 >= n || j2 < 0 || j2 >= n || res[i2][j2] != 0) {
                direction = (direction + 1) % 4;
            } else {
                res[i2][j2] = val++;
                i = i2;
                j = j2;
            }
        }
        return res;
    }
}

没有评论:

发表评论