Leetcode(59)---Spiral Matrix||

Article Directory

topic

59. Spiral Matrix II

Give you a positive integer n to generate an nxn square matrix matrix containing all elements from 1 to n2, and the elements are spirally arranged in a clockwise order.

Example 1:

Insert picture description here

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

Example 2:

输入:n = 1
输出:[[1]]

prompt:

1 <= n <= 20

Problem solution (Java)

class Solution {
    
    
    public int[][] generateMatrix(int n) 
    {
    
    
        //行坐标
        int i = 0;
        //列坐标
        int j = 0;
        //数目
        int count = 0;
        //结果矩阵
        int[][] result = new int[n][n];
        int row = n;
        while(true)
        {
    
    
            //填充从左到右的行
            for(int index = 0;index < row;index++)
            {
    
    
                //最后一个数,只加行,不加列
                if(index == row - 1)
                {
    
    
                    result[i++][j] = ++count;
                }
                else
                {
    
    
                    result[i][j++] = ++count;
                }
            }
            //判断是否已经结束
            if(count == n*n)
            {
    
    
                break;
            }
            row--;
            //填充从上到下的行
            for(int index = 0;index < row;index++)
            {
    
    
                //最后一个数,只减列,不加行
                if(index == row - 1)
                {
    
    
                    result[i][j--] = ++count;
                }
                else
                {
    
    
                    result[i++][j] = ++count;
                }
            }
            //判断是否已经结束
            if(count == n*n)
            {
    
    
                break;
            }
            //填充从右到左的行
            for(int index = 0;index < row;index++)
            {
    
    
                //最后一个数,只减行,不减列
                if(index == row - 1)
                {
    
    
                    result[i--][j] = ++count;
                }
                else
                {
    
    
                    result[i][j--] = ++count;
                }
            }
            row--;
            //判断是否已经结束
            if(count == n*n)
            {
    
    
                break;
            }
            //填充从下到上的行
            for(int index = 0;index < row;index++)
            {
    
    
                //最后一个数,只加列,不减行
                if(index == row - 1)
                {
    
    
                    result[i][j++] = ++count;
                }
                else
                {
    
    
                    result[i--][j] = ++count;
                }
            }
             //判断是否已经结束
            if(count == n*n)
            {
    
    
                break;
            }
        }
        return result;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114871988