首页 > 其他 > 详细

leetcode: Spiral Matrix II

时间:2016-04-27 02:11:24      阅读:285      评论:0      收藏:0      [点我收藏+]

问题描述:

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;
    }
}

?

leetcode: Spiral Matrix II

原文:http://shmilyaw-hotmail-com.iteye.com/blog/2293845

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!