我正在编写代码解决Leetcode上这个问题
- 对于每个单元格索引(x,y),运行深度优先搜索(dfs)
- 在每次dfs调用时,检查该单元格是否为目标单元格
- 相应地设置标志(flags)
- 如果两个标志都为true, 则将此单元格添加到"ans"向量(vector)中,否则继续下一个dfs
class Solution {
public:
void psUtil(vector<vector<int> >&mat, int x, int y, int m, int n, int &isP, int &isA, vector<vector<int> >&vis, vector<vector<int> >&ans)
{
//check dstinations
if(x == 0 || y == 0)
{
isP = 1;
}
if(x == m || y == n)
{
isA = 1;
}
vector<int> cell(2);
cell[0] = x;
cell[1] = y;
// check both dst rched
if(isA && isP)
{
// append to ans
ans.push_back(cell);
return;
}
// mark vis
vis.push_back(cell);
int X[] = {-1, 0, 1, 0};
int Y[] = {0, 1, 0, -1};
int x1, y1;
// check feasible neighbours
for(int i = 0; i < 4; ++i)
{
x1 = x + X[i];
y1 = y + Y[i];
if(x1 < 0 || y1 < 0) continue;
if(mat[x1][y1] <= mat[x][y])
{
vector<vector<int> > :: iterator it;
vector<int> cell1(2);
cell1[0] = x1;
cell1[1] = y1;
it = find(vis.begin(), vis.end(), cell1);
if(it == vis.end());
else continue;
psUtil(mat, x1, y1, m, n, isP, isA, vis, ans);
if(isA && isP) return;
}
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix)
{
// find dimensions
int m = matrix.size(); // rows
int n = matrix[0].size(); // cols
vector<vector<int> >ans;
// flags if rched destinations
int isP, isA;
isP = isA = 0;
// iterate for all indices
for(int x = 0; x < m; ++x)
{
for(int y = 0; y < n; ++y)
{
// visited nested vector
vector<vector<int> >vis;
psUtil(matrix, x, y, m, n, isP, isA, vis, ans);
isP = isA = 0;
}
}
return ans;
}
};
运行时我的错误是:
Runtime Error Message:
Line 924: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebec6 for type 'int', which requires 4 byte alignment (stl_vector.h)
Last executed input:
[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
我为什么会收到这个消息,该如何修复?
psUtil
的最后一个代码块有一段合法但看起来很奇怪的代码if(it == vis.end()); else continue;
。你真的是想要if(it != vis.end()) continue;
吗? - Michael Vekslervector::at()
方法替换所有使用vector::operator[]
的地方,这样会更早地捕捉到问题。 - Michael Vekslerif(mat[x1][y1] <= mat[x][y])
-- Change that toif(mat.at(x1).at(y1) <= mat.at(x).at(y))
- PaulMcKenzie