当前位置:网站首页>Spiral matrix

Spiral matrix

2022-07-28 08:03:00 The galloping snail has been occupied

Title Description :
Given a positive integer n, Generate a include 1 To n2 All the elements , A square matrix in which the elements are spirally arranged in a clockwise order .

Ideas :

Generate a n * n The empty matrix of , And then in order , Then simulate the whole inward surrounding filling process :

  • Define the current left and right upper and lower boundaries l,r,t,b, Initial value num = 1, Iteration termination value tar = n * n;
  • When num <= tar when , Always follow From left to right From top to bottom From right to left From bottom to top Fill in the sequence loop , After each filling :
    • perform num += 1: Get the next number to fill in ;
    • Update boundaries : For example, after filling in from left to right , Upper boundary t += 1, Equivalent to the upper boundary shrinking inward 1.

 Insert picture description here
Code :

    public static void solution(int n){
    
        int[][] a = new int[n][n];
        //l,r,t,b Define the boundary of the matrix 
        /** * l ->left * r ->right * t ->top * b ->buttom */
        int l=0,r =n-1,t=0,b=n-1;

        int number =1;
        int tar = n*n;
        while(number <= tar){
    
            /** * left -> right * */
            for(int i=l;i<=r;i++){
    
                a[t][i]=number;
                number++;
            }
            t++;

            /** * top -> buttom * */
            for (int i = t; i <=b ; i++) {
    
                a[i][r] =number ;
                number ++;
            }
            r--;

            /** * * right -> left */

            for (int i = r; i >= l ; i--) {
    
                a[b][i]=number;
                number++;
            }
            b--;

            /** * * buttom -> top */

            for (int i = b; i >=t; i--) {
    
                a[i][l]=number;
                number++;
            }
            l++;
        }


      


    }


In this paper, the reference leetcode

原网站

版权声明
本文为[The galloping snail has been occupied]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/197/202207131650329122.html