leet code 54 第二次做数组顺时针展开
2020-11-29 23:54 woshihuangrulin 阅读(101) 评论(0) 编辑 收藏 举报1, 将展开方向使用enum表示;
2,想好循环终止的条件-》转方向时下一次要访问的点越界或者已经访问过
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; if (matrix.empty()) { return result; } if (matrix.front().empty()) { return result; } int m = matrix.size() - 1; int n = matrix.front().size() - 1; vector<vector<bool>> visted(matrix.size(), vector<bool>(matrix.front().size(), false)); int i = 0; int j = 0; enum Direction {RIGHT, DOWN, LEFT, UP}; Direction dir = Direction::RIGHT; while(1) { if (dir == Direction::RIGHT) { result.emplace_back(matrix[i][j]); visted[i][j] = true; // 到达右边界或者到达上一轮访问过的位置 if (j == n || visted[i][j + 1] == true) { if (i == m || visted[++i][j]) { break; } dir = Direction::DOWN; } else if(visted[i][++j] == true) { break; } } else if (dir == Direction::DOWN) { result.emplace_back(matrix[i][j]); visted[i][j] = true; if (i == m || visted[i + 1][j] == true) { if (j == 0 || visted[i][--j]) { break; } dir = Direction::LEFT; } else if(visted[++i][j] == true) { break; } } else if (dir == Direction::LEFT) { result.emplace_back(matrix[i][j]); visted[i][j] = true; if (j == 0 || visted[i][j-1] == true) { if (i == 0 || visted[--i][j]) { break; } dir = Direction::UP; } else if (visted[i][--j] == true) { break; } } else { result.emplace_back(matrix[i][j]); visted[i][j] = true; if (i == 0 || visted[i - 1][j] == true) { if (j == n || visted[i][++j]) { break; } dir = Direction::RIGHT; } else if (visted[--i][j] == true){ break; } } } return result; } };