LeetCode最大正方形问题报addition of unsigned offset运行错误排查
错误原因排查
该运行时报错本质是vector容器的下标越界访问,具体触发原因如下:
canBeExpanded函数未做边界合法性校验:当传入的sidelength超过当前行/列可覆盖的范围时,循环变量i会递减到负数,访问matrix[i]时触发非法内存访问。- 字符与整数混用逻辑错误:
matrix中存储的是字符类型的'0'和'1',代码直接将字符值赋值给数值数组、直接和整数0比较,本质是使用ASCII值做运算,比如'1'的ASCII值为49,会导致后续计算的边长完全不符合预期,进一步放大越界概率。 - 非标准语法隐患:C++标准不支持变长数组(VLA),代码中
int Area[rows][columns]属于编译器非标准扩展,存在内存布局异常的风险。 - 浮点数精度风险:
sqrt返回浮点类型,直接参与整数运算可能出现精度损失(例如9开方得到2.9999999999,转整数后变为2),导致边长计算错误。
修复方案
对应修改代码如下:
// 增加边界校验,参数改为const引用避免大矩阵拷贝 bool canBeExpanded(int c_row, int c_col, int sidelength, const vector<vector<char>>& matrix) { // 提前判断边界合法性,避免越界 if (c_row - sidelength + 1 < 0 || c_col - sidelength + 1 < 0) { return false; } for(int i = c_row; i > c_row - sidelength; i--) { // 对比字符'0'而不是整数0 if(matrix[i][c_col] == '0') { return false; } } for(int i = c_col; i > c_col - sidelength; i--) { if(matrix[c_row][i] == '0') { return false; } } return true; } int maximalSquare(vector<vector<char>>& matrix) { int rows = matrix.size(); if (rows == 0) return 0; int columns = matrix[0].size(); // 用标准vector替代变长数组,存储边长而非面积避免开方运算 vector<vector<int>> dp(rows, vector<int>(columns, 0)); int maxSide = 0; // 边界初始化,字符转整数 for(int c_row = 0; c_row < rows; c_row++) { for(int c_col = 0; c_col < columns; c_col++) { dp[c_row][c_col] = matrix[c_row][c_col] - '0'; if (dp[c_row][c_col] == 1) { maxSide = 1; } } } for(int c_row = 1; c_row < rows; c_row++) { for(int c_col = 1; c_col < columns; c_col++) { if (dp[c_row-1][c_col-1] > 0) { int expectSide = dp[c_row-1][c_col-1] + 1; if (canBeExpanded(c_row, c_col, expectSide, matrix)) { dp[c_row][c_col] = expectSide; maxSide = max(maxSide, dp[c_row][c_col]); } else { // 拓展失败时取当前单元格本身的值,避免保留垃圾值 dp[c_row][c_col] = matrix[c_row][c_col] - '0'; } } } } // 最大面积为最大边长的平方 return maxSide * maxSide; }
内容的提问来源于stack exchange,提问作者SachinKaranwal
相关产品推荐
相关产品推荐

