[leedcode 59] 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 ]
]
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++;
        }
        
    }
}

 

posted @ 2015-07-13 10:52  ~每天进步一点点~  阅读(120)  评论(0编辑  收藏  举报