Monday, April 14, 2014

LeetCode: Spiral Matrix I && II


Spiral Matrix I



Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

这个问题难点在外层for循环的结束条件. Have to pay attention to Line 27 and Line 31 to break the outer loop so as to deal with matrix like [[1,11],[2, 12],[3, 13],[4, 14],[5, 15],[6, 16],[7, 17]]. In addition, It doesn't affect the result if commenting out line 10 to line 14, but line 16 to line 21 are necessary





Spiral Matrix II
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 ]
]



Not difficult in the algorithm, but need to be carefully about the index.
Had a little problem with the two dimensional vector. In order to access it with [][], matrix has to be initialized. Vecter<int> v(n) is to set the length of v to n.




No comments:

Post a Comment