欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > leetcode 885. Spiral Matrix III

leetcode 885. Spiral Matrix III

2025/7/25 8:53:38 来源:https://blog.csdn.net/wuyexiaobailong/article/details/141277282  浏览:    关键词:leetcode 885. Spiral Matrix III

题目链接

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

题解:

Medium的题无需多言,直接上代码:

class Solution {
public:vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {int drc[4][2] = {{0,1},{1,0},{0,-1},{-1,0}},dn = 0, dp[2] = {1,1}, end = rows*cols, ln=0;vector<vector<int>> rst(end, {0,0});rst[ln][0] = rStart;rst[ln++][1] = cStart;while(ln < end) {for(int i = 0; i< dp[dn&1]; i++) {rStart += drc[dn][0];cStart += drc[dn][1];if (isInMatrix(rStart, rows) && isInMatrix(cStart, cols)) {rst[ln][0] = rStart;rst[ln++][1] = cStart;}}++dp[dn&1];(++dn) %= 4;}return rst;}inline bool isInMatrix(int x, int ln) {return x>= 0 && x <ln;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词