Decription:
We are gonna make the variable name "Top, bottom, right_col, left_col to point the row and column you are currently in.
Solution:
We set the top and bottom to point to the first row and the last row.
Next, we set left_column and right_column to point to the first column and the last column.
We can see the sprial matrix gets value following this order: top row --> right most column --> bottom row --> left most column.
First loop(top row):
example 1)
from matrix[top][0] to matrix[top][2], so the range should be range(left_col, right_col) --> (0 <= i < 3)
Second loop(right most column):
example 1)
from matrix[1][right_col] to matrix[2][right_col], so the range should be range(top, bottom) --> (1 <= i < 3)
Third loop(bottom row):
example 1)
from matrix[bottom - 1(2)][1] to matrix[bottom -1(2)][0],
so the range should be range(right_col - 1, left_col -1, -1) --> (1 >= i > -1)
Fourth loop(left most column):
example 1)
just matrix[1][left_col]
so the range should be range(bottom-1, top-1, -1) --> (1 >= i > 0)
And we return the result. Then, let's talk about the break between the second and third loop.
In case2, we can see the the result list is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6] without the break.
The third loop works twice, and it puts the 6 again.
6 should be the duplication number, because we put 6 after the seond time of first loop.
So, that's why we should put the break on our codes.
Time complexity O(m*n)
Space complexity: O(1)
'LeetCode ๐๏ธ > Matrix' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
79. Word Search (0) | 2023.02.13 |
---|---|
48. Rotate Image (0) | 2023.02.06 |
73. Set Matrix Zeroes (0) | 2023.02.02 |