1

题目要求

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

也就是将递加的数字按照顺时针的顺序依次填入数组之中

这道题目联系到Spiral Matrix I,其实就相当好解决了。Spiral Matrix I可以参考我的这篇博客

具体代码

在参考完这篇博客后,就会发现,这里其实就是将读取数据反过来改为填入数据,代码如下:

    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int rowStart = 0;
        int rowEnd = n-1;
        int colStart = 0;
        int colEnd = n-1;
        
        int number = 1;
        while(rowStart<=rowEnd && colStart<=colEnd){
            for(int i = colStart ; i<=colEnd ; i++){
                result[rowStart][i] = number;
                number++;
            }
            
            rowStart++;
            
            for(int i = rowStart ; i<=rowEnd ; i++){
                result[i][colEnd] = number;
                number++;
            }
            colEnd--;
            
            if(rowStart <= rowEnd){
                for(int i = colEnd ; i>=colStart ; i--){
                    result[rowEnd][i] = number;
                    number++;
                }
            }
            rowEnd--;
            
            if(colStart<= colEnd){
                for(int i = rowEnd ; i>= rowStart ; i--){
                    result[i][colStart] = number;
                    number++;
                }
            }
            colStart++;
        }
        return result;
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行