# [LeetCode] 54. Spiral Matrix

```class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []

n_row, n_col = len(matrix), len(matrix[0])
result = []
visited = [[False for i in range(n_col)] for j in range(n_row)]
row, col, x = 0, 0, 0
delta = [[0,1], [1, 0], [0, -1], [-1, 0]]
for _ in range(n_row * n_col):
result.append(matrix[row][col])
visited[row][col] = True
new_row = row + delta[x % 4][0]
new_col = col + delta[x % 4][1]
if self.will_change_direction(new_row, new_col, visited):
x += 1
row += delta[x % 4][0]
col += delta[x % 4][1]

return result

def will_change_direction(self, row, col, visited):
if row < 0 or row >= len(visited):
return True
if col < 0 or col >= len(visited[0]):
return True
if visited[row][col]:
return True
return False
```

```public class Solution {
public List spiralOrder(int[][] matrix) {

List res = new ArrayList();

if (matrix.length == 0) {
return res;
}

int rowBegin = 0;
int rowEnd = matrix.length-1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;

while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j ++) {
}
rowBegin++;

// Traverse Down
for (int j = rowBegin; j <= rowEnd; j ++) {
}
colEnd--;

if (rowBegin <= rowEnd) {
// Traverse Left
for (int j = colEnd; j >= colBegin; j --) {
}
}
rowEnd--;

if (colBegin <= colEnd) {
// Traver Up
for (int j = rowEnd; j >= rowBegin; j --) {