`
frank-liu
  • 浏览: 1666057 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

leetcode: Spiral Matrix II

 
阅读更多

问题描述:

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 ]
]

原问题链接:https://leetcode.com/problems/spiral-matrix-ii/

 

问题分析

  这个问题和前面的Spiral Matrix 基本上差不多,前面是要求按照这种方式遍历整个矩阵,这里是按照这个方式给矩阵里的元素赋值。所以可以在原来的基础上稍微修改一点直接搬过来就可以了。详细的代码实现如下:

 

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1, count = 1;
        while(rowBegin <= rowEnd && colBegin <= colEnd) {
            for(int i = colBegin; i <= colEnd; i++) {
                matrix[rowBegin][i] = count;
                count++;
            }
            rowBegin++;
            for(int i = rowBegin; i <= rowEnd; i++) {
                matrix[i][colEnd] = count;
                count++;
            }
            colEnd--;
            if(rowBegin <= rowEnd) {
                for(int i = colEnd; i >= colBegin; i--) {
                    matrix[rowEnd][i] = count;
                    count++;
                }
            }
            rowEnd--;
            if(colBegin <= colEnd) {
                for(int i = rowEnd; i >= rowBegin; i--) {
                    matrix[i][colBegin] = count;
                    count++;
                }
            }
            colBegin++;
        }
        return matrix;
    }
}

 

1
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics