[leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印
Posted November 23, 2013
on:- In: leetcode
- 5 Comments
遇见这种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: matrix
5 Responses to "[leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印"

感觉楼主的bf好厉害 😀

March 9, 2014 at 8:48 pm
this is a clever way! thanks!!
March 9, 2014 at 9:16 pm
glad it’s helpful 🙂