I am trying to count and update the immediate neighbors of a cell with non zero values. So left, right, upper, lower, upper-left ... Anyway all the eight directions and the cell itself.
int grid[100][100];
int genNeibrs(int x, int y, int n, int m)
{
m--;
n--;
int c = 0, xs = ((x - 1) < 0) ? 0 : (x - 1),
xe = ((x + 1) > n) ? n : (x + 1),
ys = ((y - 1) < 0) ? 0 : (y - 1),
ye = ((y + 1) > m) ? m : (y + 1);
for (auto i = xs; i <= xe; i++)
{
for (auto j = ys; j <= ye; j++)
{
if (grid[i][j])
++c;
}
}
return c;
}
void getGrs(int n, int m)
{
for (auto i = 0; i < n; i++)
{
for (auto j = 0; j < m; j++)
if (grid[i][j])
{
int q = genNeibrs(i, j, m, n);
if (q)
grid[i][j] = q;
}
}
}
Here the value of q becomes 0 for successive iterations other than 0,0 for
grid = {{1, 0, 1, 1, 0, 1, 1, 1, 1, 0 <repeats 91 times>}, {0, 0, 0, 1, 0, 1, 0, 0, 1, 0 <repeats 91 times>}, {0 <repeats 100 times>} <repeats 98 times>}
, m and n being 9 and 2 respectively.
While debugging with gdb the function genNeibrs
returns as expected but over execution I managed to pin it down to the line where q is being initialized. It somehow gets initialized to zero even when it shouldn't.
So what am I doing wrong?
Expected value of grid = {{1, 0 ,3 ,3 ,0, 3, 4, 5, 3, 0 <repeats 91 times>},{0, 0, 0, 3, 0, 3, 0, 0, 3, 0 <repeats 91 times>}, {0 <repeats 100 times>} <repeats 98 times>}
Anyway the grid's values doesn't change.
答案 0 :(得分:3)
首先,在调试时,您应该进入有问题的功能,以查看其中出了什么问题。但是,由于在寻找那些使用隐秘编码风格的打字机时发现了可疑代码,请比较以下几行。
int genNeibrs(int x, int y, int n, int m)
int q = genNeibrs(i, j, m, n);
告诉我,如果您将“ m和n分别为2和9”而不是“ m和n分别为9和2”会发生什么情况?
课程: 使用有意义的变量名!字母“ m”和“ n”在外观上相似。与“ m”和“ n”相比,发现“行”和“列”被反转要容易得多。