题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
class Solution {
private:
vector<int> target;
vector<vector<bool>> record;
vector<vector<int> > matrix_;
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
matrix_ = matrix;
int row = matrix.size();
int col = matrix[0].size();//没有空的输入
record = vector<vector<bool>>(row+2,vector<bool>(col+2,true));//使用↕↔各自扩展1维的二维bool表记录
//边界设置为false,这样只能遍历路径还是true的位置,而遍历之后,true就改成false
for (int i = 0; i < col + 2; i++) record[0][i] = false, record[row + 1][i] = false;
for (int j = 0; j < row + 2; j++) record[j][0] = false, record[j][col+1] = false;
//递归,从1,1左上角开始
go_next(1,1);
return target;
}
private:
void go_next(int y,int x)
{
target.push_back(matrix_[y-1][x-1]);//加入路径
record[y][x] = false;//遍历过了,设置为false
//规定顺时针,按→↓←↑的顺序依次进行就可以了,二维bool表是关键
if(record[y][x+1] &&! record[y-1][x])//→ 添加 &&!的条件:
//比如图里9的位置,既能↑也可以→的情况下,优先向上移动,第一次没加只过了9组用例
go_next(y,x+1);
else if(record[y+1][x])//↓
go_next(y+1,x);
else if(record[y][x-1])//←
go_next(y,x-1);
else if(record[y-1][x])//↑
go_next(y-1,x);
}
};

查看11道真题和解析