54. Spiral Matrix - cocoder39/coco39_LC GitHub Wiki
Writing clean code under time pressure is challenging
it is easy to miss the 4 break conditions within the while loop, which caused bug eg suppose up is already > down after executing 1st for loop, and right is still >= left then the 3rd for loop will be executed
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
up, down, left, right = 0, len(matrix)-1, 0, len(matrix[0])-1
while up <= down and left <= right:
for i in range(left, right+1):
res.append(matrix[up][i])
up += 1
if up > down:
break
for i in range(up, down+1):
res.append(matrix[i][right])
right -= 1
if left > right:
break
for i in range(right, left-1, -1):
res.append(matrix[down][i])
down -= 1
if up > down:
break
for i in range(down, up-1, -1):
res.append(matrix[i][left])
left += 1
if left > right:
break
return res
=================================================================
play with the boundary, break the loop as soon as there is a violation
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return {};
int n = matrix[0].size();
vector<int> res;
int left = 0, right = n - 1, low = m - 1, high = 0;
while (true) {
for (int i = left; i <= right; i++) {
res.push_back(matrix[high][i]);
}
if (++high > low) break;
for (int i = high; i <= low; i++) {
res.push_back(matrix[i][right]);
}
if (--right < left) break;
for (int i = right; i >= left; i--) {
res.push_back(matrix[low][i]);
}
if (--low < high) break;
for (int i = low; i >= high; i--) {
res.push_back(matrix[i][left]);
}
if (++left > right) break;
}
return res;
}
an implementation like below cannot pass
[[2,3]]
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return {};
int n = matrix[0].size();
vector<int> res;
int left = 0, right = n - 1, low = m - 1, high = 0;
while (left <= right && high <= low) {
for (int i = left; i <= right; i++) {
res.push_back(matrix[high][i]);
}
++high;//if (++high > low) break;
for (int i = high; i <= low; i++) {
res.push_back(matrix[i][right]);
}
--right;//if (--right < left) break;
for (int i = right; i >= left; i--) {
res.push_back(matrix[low][i]);
}
--low;//if (--low < high) break;
for (int i = low; i >= high; i--) {
res.push_back(matrix[i][left]);
}
++right;//if (++left > right) break;
}
return res;
}