[leetcode-59]spiral matrixII(java)

原创 2015年07月10日 19:35:45

问题描述:
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-Java】54. Spiral Matrix+59. Spiral Matrix II

54. Spiral Matrix: 1.原题 链接:https://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n e...

LeetCode#59. Spiral Matrix II

题目:给定一个整数n,以螺旋形将1到n^2填充螺旋矩阵

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

LeetCode 54/59. Spiral Matrix i, ii

1. 题目描述54 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix ...

leetcode 59. Spiral Matrix II

我在这里用了和leetcode 54 一样的思路开辟了一个和原矩阵同样大小的矩阵temp来存放是否输出过的标志位,然后按照向右,向左,向上,向下的顺时针顺序构造矩阵。 下面是这两道题的代码:...

[LeetCode]59.Spiral Matrix II

【题目】 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral orde...

leetcode || 59、 Spiral Matrix II

problem: Given an integer n, generate a square matrix filled with elements from 1 to n2...

LeetCode --- 59. Spiral Matrix II

题目链接:Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 to n...

Leetcode59. Spiral Matrix II

59. Spiral Matrix II 1、原题 Given an integer n, generate a square matrix filled with elements from 1...

leetcode 59. Spiral Matrix II-螺旋矩阵|清晰思路

原题链接:59. Spiral Matrix II 【思路】 遍历图解如上图所示,n 分为偶数和奇数两种情况。当 n 为偶数时,最后一次遍历刚好添加完毕;当 n 为奇数时,最后还需要进行一次添加操...

【LEETCODE】59-Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. Fo...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)