LeetCode Spiral Matrix II

Title description:

Give you a positive integer  n , generate a  square matrix  containing  1 all elements up to n^2 and the elements are arranged spirally in clockwise order   .n x nmatrix

class Solution {
    public int[][] generateMatrix(int n) {
        int row = n;  //行数
        int col = n;  //列数
        int[][] matrix = new int[row][col];
        int count=1;
        int startr=0;  //确定当前的起始行坐标
        int endr=row-1;  //确定当前的结束行坐标
        int startc=0;  //确定当前的起始列坐标
        int endc=col-1;  //确定当前结束的列坐标
        while(true){
            
            //往右边走 列坐标增加 行坐标不变
            for(int j=startc;j<=endc;j++){
                matrix[startr][j]=count++;
            }
            startr++;

            //往下走 列坐标不变 行坐标增加
            for(int i=startr;i<=endr;i++){
                matrix[i][endc]=count++;
            }
            endc--;

            //往左走 行坐标不变  列坐标减少
            for(int j=endc;j>=startc;j--){
                matrix[endr][j]=count++;
            }
            endr--;

            //往上走 列坐标不变 行坐标减少

            for(int i=endr;i>=startr;i--){
                matrix[i][startc]=count++;
            }
            startc++;
            
            if(count>n*n){
                break;
            }
        }
        return matrix;
    }
}

It's been a long time since I haven't solved the problem, my mind is confused.

Guess you like

Origin blog.csdn.net/kidchildcsdn/article/details/114239216