I am not able to find where is my vector going out of bound. This is solution of leetcode question 695.
Error:
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
Code:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> vis(n,vector<int>(m,0));
int ans =0 ;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
int count = 0;
if(grid[i][j]==1 && !vis[i][j]) {
vis[i][j]=1;
queue<pair<int,int>> q;
q.push({i,j});
count++;
while(!q.empty()) {
int a = q.front().first;
int b = q.front().second;
q.pop();
int r[] = {-1, 1, 0, 0};
int c[] = {0, 0, 1, -1};
for(int z=0; z<4; z++) {
int x = a + r[z];
int y = b + c[z];
if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) {
vis[x][y]=1;
q.push({x,y});
count++;
}
}
}
ans = max(ans,count);
}
}
}
return ans;
}
I expect
if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) {
should be
if (x>=0 && y>=0 && x<n && y<m && grid[x][y]==1 && !vis[x][y]) {
Notice in the error addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028
. In other words the unsigned offset is negative (when regarded as a signed quantity).
Always be careful mixing signed and unsigned arithmetic.