JunyiCode
3/24/2020 - 5:52 PM

59. Spiral Matrix II

/*
&& count <= n * n防止最中间一位出错
*/

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int left = 0, up = 0, right = n - 1, down = n - 1;
        int count = 1;
         
        while(count <= n * n) {
            for(int i = left; i <= right && count <= n * n; i++) {
                res[left][i] = count;
                count++;
            }
            for(int i = up + 1; i <= down && count <= n * n; i++) {
                res[i][right] = count;
                count++;
            }
            for(int i = right - 1; i >= left && count <= n * n; i--) {
                res[down][i] = count;
                count++;
            }
            for(int i = down - 1; i >= up + 1 && count <= n * n; i--) {
                res[i][left] = count;
                count++;
            }
            left++; right--; up++; down--;
        }
        
        return res;
    }
}