螺旋算法的matlab代码
时间: 2023-08-04 15:04:37 浏览: 179
以下是 MATLAB 代码实现:
```matlab
function res = spiralOrder(matrix)
if isempty(matrix)
res = [];
return
end
[m, n] = size(matrix);
res = zeros(m * n, 1);
left = 1; right = n; top = 1; bottom = m;
k = 1;
while left <= right && top <= bottom
for j = left:right
res(k) = matrix(top, j);
k = k + 1;
end
for i = top + 1:bottom
res(k) = matrix(i, right);
k = k + 1;
end
if left < right && top < bottom
for j = right - 1:-1:left
res(k) = matrix(bottom, j);
k = k + 1;
end
for i = bottom - 1:-1:top + 1
res(k) = matrix(i, left);
k = k + 1;
end
end
left = left + 1; right = right - 1;
top = top + 1; bottom = bottom - 1;
end
res = res(1:k - 1);
end
```
同样,`matrix` 是一个二维矩阵,`res` 是遍历后得到的一维数组。该算法的时间复杂度与空间复杂度同样为 $O(mn)$。值得注意的是,MATLAB 中数组的索引从 $1$ 开始,因此代码中下标是从 $1$ 开始的。
阅读全文