gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { int m =…
- User
class Solution { public: vector spiralOrder(vector<vector>& matrix) { int m = matrix.size(); int n = matrix[0].size(); vector res;
int right = 0, left = n - 1, top = 0, bottom = m - 1; while(right <= left && bottom <= top) { if(right == left && bottom == top) res.push_back(matrix[top][right]);… return res; } };
为什么结果是空的
- Assistant
你这段代码的主要问题在于边界变量的定义和循环条件有误,导致循环体根本没有执行,因此结果是空的。
具体问题分析:
- 变量命名和初始化上:
int right = 0, left = n - 1, top = 0, bottom = m - 1;这里
right应该表示右边界,left应该表示左边界,但是你给right赋值为0,left赋值为n - 1,两者关系相反。通常应是:int left = 0, right = n - 1, top = 0, bottom = m - 1;- 循环条件:
while(right <= left && bottom <= top)