本题经过一下午的思考,终于解出来了。使用的是层次遍历的思想。

class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int RowLen = matrix.size() - ;
int ColLen = matrix[].size() - ;
int N = RowLen + ColLen;
int i = RowLen;
int j = ;
queue<pair<int, int>> Q; Q.push(make_pair(i, j));
while (!Q.empty())
{
//全部出队,加入vector
vector<pair<int, int>> V;
while (!Q.empty())
{
pair<int, int> p = Q.front();
Q.pop();
V.push_back(p);
cout << p.first << " " << p.second << endl;
}
cout << "------------------------------------------" << endl; //遍历V
int base = matrix[V[].first][V[].second];
set<pair<int, int>> S;
for (auto v : V)
{
//判断是否都是相同的数值
if (base != matrix[v.first][v.second])
{
return false;
} //判断“上”和“右”的元素是否合法,
int Up_x = v.first - ;
int Up_y = v.second;
//“上元素”合法则加入S(去重)
if (Up_x >= && S.find(make_pair(Up_x, Up_y)) == S.end())
{
S.insert(make_pair(Up_x, Up_y));
} int Right_x = v.first;
int Right_y = v.second + ;
//“右元素”合法则加入S(去重)
if (Right_y <= ColLen && S.find(make_pair(Right_x, Right_y)) == S.end())
{
S.insert(make_pair(Right_x, Right_y));
}
} //将S中的元素,添加到Q中
for (auto s : S)
{
Q.push(s);
}
}
return true;
}
};
05-11 15:01