leetcode brush 21 title

Today's topic is LeetCode brush 59 questions, https://leetcode-cn.com/problems/spiral-matrix-ii/ , requires that the question is:

Given a positive integer  n- , containing 1 to generate a  n- 2 all of the elements, and the element arranged spirally clockwise order square matrix. such as:

Input: 3 
Output: 
[ 
 [1, 2, 3], 
 [8,9, 4], 
 [7, 6, 5] 
] 
This code is also very good write, I use is simple while loop, in particular the following:
public  class GenerateMatrix_59_middle {
     public  static  void main (String [] args) { 
        Generate ( . 5 ); 
    } 
    public  static  int [] [] Generate ( int n-) {
         int [] [] Result = new new  int [n-] [n-]; // output final result 
        Boolean [] [] = hasNumber new new  Boolean [n-] [n-]; // determines whether this position if an element 
        int I =. 1 ;
         int X = 0 ;
         int Y = 0 ;
         the while ( i <= n *n){
            if (hasNumber[x][y]==false){
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }else {
                if (y+1<n&&hasNumber[x][y+1]==false)y=y+1;
                else if (x+1<n&&hasNumber[x][y+1]==false)x=x+1;
                else if (y-1>=0&&hasNumber[x][y+1]==false)y=y-1;
                else if (x-1>=0&&hasNumber[x][y+1]==false)x=x-1;
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }
            while (y+1<n&&hasNumber[x][y+1]==false){
                y=y+1;
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }
            while (x+1<n&&hasNumber[x+1][y]==false){
                x=x+1;
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }
            while (y-1>=0&&hasNumber[x][y-1]==false){
                y=y-1;
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }
            while (x-1>=0&&hasNumber[x-1][y]==false){
                x=x-1;
                result[x][y]=i;
                hasNumber[x][y]=true;
                i++;
            }
        }
        for (int j = 0; j <n ; j++) {
            for (int k = 0; k <n ; k++) {
                System.out.print(result[j][k]+"---");
            }
            System.out.println();
        }
        return  result;
    }
}

 

Guess you like

Origin www.cnblogs.com/cquer-xjtuer-lys/p/11481173.html