Middle-题目29:59. Spiral Matrix II

题目原文:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
题目大意:
给一个整数n,输出n*n的方阵,其中1~ n2 以顺时针的螺旋方式填充。
题目分析:
就是简单的模拟,从1开始往里填,注意拐弯的临界条件(走到数组的边缘或者按原方向的下一位已经填好数)。
源码:(language:java)

public class Solution {
    private  final int RIGHT = 1;
    private  final int DOWN = 2;
    private  final int LEFT = 3;
    private  final int UP = 4;
    public  int[][] generateMatrix(int n) {
        int direction = 1;//1,2,3,4 stand for RIGHT,DOWN,LEFT,UP respectively.
        int row=0,col=0;//current position
        int[][] matrix = new int[n][n];
        for(int i=1;i<=n*n;i++) {
            matrix[row][col] = i;
            switch (direction) {
                case RIGHT: {                   
                    if(col+1 == n || matrix[row][col+1] != 0) {
                        direction=DOWN;
                        row++;
                    }
                    else
                        col++;
                    break;
                }
                case DOWN: {
                    if(row+1 == n || matrix[row+1][col] != 0) {
                        direction=LEFT;
                        col--;                      
                    }
                    else
                        row++;
                    break;
                }
                case LEFT: {
                    if(col == 0 || matrix[row][col-1] != 0) {
                        direction=UP;
                        row--;
                    }
                    else
                        col--;
                    break;
                }
                case UP: {
                    if(matrix[row-1][col] != 0) {
                        direction=RIGHT;
                        col++;
                    }
                    else
                        row--;
                }
            }
        }
        return matrix;
    }
}

成绩:
0ms,beats 14.13%,众数0ms,85.87%

你可能感兴趣的:(Middle-题目29:59. Spiral Matrix II)