coding4ever

[Leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印

Java 版本代码如下:

public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int value = 1;
        int left = 0, right = n-1, top = 0, bottom = n-1;
        while(top < bottom && left < right)
        {
            //corresponding to the red part
            for(int j = left; j < right; j++)
            {
                res[top][j] = value++;
            }
            //corresponding to the blue part
            for(int i = top; i < bottom; i++)
            {
                res[i][right] = value++;
            }
            //corresponding to the yellow part
            for(int j = right; j > left; j--)
            {
                res[bottom][j] = value++;
            }
            //corresponding to the purple part
            for(int i = bottom; i > top; i--)
            {
                res[i][left] = value++;
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        if(n%2!=0) res[n/2][n/2]=value;
        return res;
    }

 

思路,定义四个变量 top, bottom, left, right分别bound住四边。然后可以按照下图的方法填充res矩阵。填充顺序是(1) 红色,(2) 蓝色,(3) 绿色,(4) 紫色。

把最外面填充完全后。开始top++, bottom--, left++, right--来把四个边往里面移。

* 如果n是奇数,最后中间那个值要单独处理, res[n/2][n/2] = k.

 

原题: https://leetcode.com/problems/spiral-matrix-ii/#/description

转载至:https://leetcodenotes.wordpress.com/2013/11/23/leetcode-spiral-matrix-%E6%8A%8A%E4%B8%80%E4%B8%AA2d-matrix%E7%94%A8%E8%9E%BA%E6%97%8B%E6%96%B9%E5%BC%8F%E6%89%93%E5%8D%B0/

posted on 2017-03-15 07:35  coding4ever  阅读(205)  评论(0编辑  收藏  举报

导航