本题经过一下午的思考,终于解出来了。使用的是层次遍历的思想。
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int RowLen = matrix.size() - 1; int ColLen = matrix[0].size() - 1; int N = RowLen + ColLen; int i = RowLen; int j = 0; 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[0].first][V[0].second]; set<pair<int, int>> S; for (auto v : V) { //判断是否都是相同的数值 if (base != matrix[v.first][v.second]) { return false; } //判断“上”和“右”的元素是否合法, int Up_x = v.first - 1; int Up_y = v.second; //“上元素”合法则加入S(去重) if (Up_x >= 0 && 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 + 1; //“右元素”合法则加入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; } };