c++ - 这个 C++ 片段中的缓冲区溢出在哪里?
问题描述
我使用以下解决方案遇到缓冲区溢出https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
class Solution {
public:
struct pt {
int x;
int y;
int k;
int s;
pt(int x, int y, int k, int s): s(s), x(x), y(y), k(k) {}
};
int shortestPath(vector<vector<int>>& grid, int k) {
int height = grid.size(), width = grid[0].size();
std::vector<std::pair<int, int>> dirs {{1,0}, {0, 1}, {-1, 0}, {0, -1}};
std::vector<std::vector<int>> maxKs(height, std::vector<int>(width, -1));
std::queue<pt> q;
q.push(pt(0, 0, k, 0));
while ( !q.empty() ) {
auto f = q.front();
q.pop();
if (f.x == width-1 && f.y == height-1) return f.s;
if (maxKs[f.x][f.y] >= f.k || f.k < 0) continue;
maxKs[f.x][f.y] = f.k;
for (auto dir : dirs) {
int x = f.x + dir.first;
int y = f.y + dir.second;
if (x < 0 || y < 0 || x == width || y == height) continue;
int curK = f.k - (grid[x][y] == 1);
if (curK < 0) continue;
q.push(pt(x,y,curK,f.s + 1));
}
}
return -1;
}
};
想知道是否有人对这里发生的事情有想法?
解决方案
您将尺寸声明为
int height = grid.size(), width = grid[0].size();
但是您使用width
的是 的元素数grid
和height
的数grid[x]
。
maxKs[f.x][f.y]
应该是maxKs[f.y][f.x]
,grid[x][y]
应该是grid[y][x]
。
推荐阅读
- database - 自动缩放实例 Web 和数据库服务器
- bash - 是否可以对 bash 自动完成输出进行分类?
- ssl-certificate - 邮递员测试:预计 SSL 证书到期日
- javascript - Chrome 扩展消息无法通过
- csv - Neo4j 为 CSV 导出指定字段和列名
- python - 在numpy数组中搜索
- python - 使用 Python 3.x 运行一个简单的本地 HTTP 服务器
- python - 如何分配字典中的值?(Python)
- java - 我正在尝试在树莓派上设置 Minecraft 服务器,但我在首次启动服务器时一直遇到错误
- r - 将字符分隔到新列中