[leetcode-59]spiral matrixII(java)

问题描述:
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 类似

代码如下:

public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        //init result
        for(int i = 0;i<n;i++)
            for(int j = 0;j<n;j++)
                result[i][j] = 0;

        int index = 0;
        int num = n*n;
        int row = 0,col = -1;
        while(index<num){
            for(col = col+1;col<n;col++){
                if(result[row][col]!=0)
                    break;
                result[row][col] = ++index;
            }
            col--;
            for(row = row+1;row<n;row++){
                if(result[row][col]!=0)
                    break;
                result[row][col] = ++index;
            }
            row--;
            for(col = col-1;col>=0;col--){
                if(result[row][col] != 0)
                    break;
                result[row][col] = ++index;
            }
            col++;
            for(row = row-1;row>=0;row--){
                if(result[row][col] != 0)
                    break;
                result[row][col] = ++index;
            }
            row++;
        }
        return result;
    }
阅读更多
文章标签: leetcode 算法
个人分类: leetcode
上一篇【leetcode-49】Anagrams(java)
下一篇[leetcode-41]First Missing Positive(java)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭