简单题。但做得不简洁。里面用了一个count来计数,还是不错的。因为有可能只有一行(或子状态中),那么m_low == m_high,这时,当m_low++后,m_high大于m_low,可能会从左往右和回扫都是同一行。
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ans = new ArrayList<Integer>();
int m = matrix.length;
if (m == 0) return ans;
int n = matrix[0].length;
if (n == 0) return ans;
int m_low = 0;
int m_high = m-1;
int n_low = 0;
int n_high = n-1;
int count = m*n;
while (count > 0) {
for (int i = n_low; i <= n_high && count > 0; i++) {
ans.add(matrix[m_low][i]);
count--;
}
m_low++;
for (int i = m_low; i <= m_high && count > 0; i++) {
ans.add(matrix[i][n_high]);
count--;
}
n_high--;
for (int i = n_high; i >= n_low && count > 0; i--) {
ans.add(matrix[m_high][i]);
count--;
}
m_high--;
for (int i = m_high; i >= m_low && count > 0; i--) {
ans.add(matrix[i][n_low]);
count--;
}
n_low++;
}
return ans;
}
}
Python3
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
if m == 0:
return []
n = len(matrix[0])
if n == 0:
return []
ret = []
i = j = 0
cnt = 0
direction = 0 # 0, 1, 2, 3
upper_bound = 0
lower_bound = m - 1
left_bound = 0
right_bound = n - 1
upper_bound += 1
while cnt < m * n:
ret.append(matrix[i][j])
if direction == 0:
if j != right_bound:
j += 1
else:
right_bound -= 1
i += 1
direction = 1
elif direction == 1:
if i != lower_bound:
i += 1
else:
lower_bound -= 1
j -= 1
direction = 2
elif direction == 2:
if j != left_bound:
j -= 1
else:
left_bound += 1
i -= 1
direction = 3
elif direction == 3:
if i != upper_bound:
i -= 1
else:
upper_bound += 1
j += 1
direction = 0
cnt += 1
return ret