Lexi's Leetcode solutions

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

Posted on: November 23, 2013

遇见这种matrix题就腿发软,bf给讲了个四条边bound的方法,立刻15分钟bug free了。高兴够呛。

public int[][] generateMatrix(int n) {
    int[][] res = new int[n][n];
    int k = 1;
    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    while (left < right && top < bottom) {
        for (int j = left; j < right; j++) {
            res[top][j] = k++;
        }
        for (int i = top; i < bottom; i++) {
            res[i][right] = k++;
        }
        for (int j = right; j > left; j--) {
            res[bottom][j] = k++;
        }
        for (int i = bottom; i > top; i--) {
            res[i][left] = k++;
        }
        left++;
        right--;
        top++;
        bottom--;
    }
    if (n % 2 != 0)
        res[n / 2][n / 2] = k;
    return res;
}
Tags:

5 Responses to "[leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印"

this is a clever way! thanks!!

glad it’s helpful 🙂

感觉楼主的bf好厉害 😀

哈哈,每个程序员妹子背后都有一个默默给做作业的男人。。

看来我也有必要找个bf…
另外你贴代码的时候怎么maintain里面的格式的呢. 我贴上去都是左对其了.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog Stats

  • 222,875 hits
November 2013
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  
%d bloggers like this: