首页 > 其他 > 详细

[leedcode 59] Spiral Matrix II

时间:2015-07-13 11:38:02      阅读:280      评论: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 ]
]
public class Solution {
    int res[][];
    int val=1;
    public int[][] generateMatrix(int n) {
        //主要是通过画图,判断每个分支的范围,本题还适应非方阵
         res=new int[n][n];
        int minRow=0;
        int maxRow=n-1;
        int minCol=0;
        int maxCol=n-1;
        int val=1;
        while(minRow<=maxRow&&minCol<=maxCol){
            generate(minRow,maxRow,minCol,maxCol);
            minRow++;
            maxRow--;
            minCol++;
            maxCol--;
        }
        return res;
    }
    public void generate(int minRow,int maxRow,int minCol,int maxCol){
        for(int i=minCol;i<=maxCol;i++){
            res[minRow][i]=val++;
        }
        for(int i=minRow+1;i<=maxRow;i++){
            res[i][maxCol]=val++;
        }
        for(int i=maxCol-1;i>=minCol;i--){
            res[maxRow][i]=val++;
        }
        for(int i=maxRow-1;i>minRow;i--){
            res[i][minCol]=val++;
        }
        
    }
}

 

[leedcode 59] Spiral Matrix II

原文:http://www.cnblogs.com/qiaomu/p/4642303.html

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