稍作重组。我们可以将行邻接测试和列邻接测试组合成一个循环。
检查给定行时,我们可以与该行的前一个值进行比较。但是,我们也可以将值与下一行中它下面的值进行检查。
我们可以在行值的单个循环中执行此操作。所以,我们只需要一个 套嵌套的for 循环而不是两个。
我们在末尾添加一个特殊的循环来检查最后一行[没有检查下一行]。
此外,通过添加一些额外的int * 指针来指向要比较的行,我们可以简化board 矩阵索引并消除一些重复的额外指针/值提取。
这是重构的代码。有注释:
typedef struct game {
int h;
int n;
int **board;
} game_t;
int
check(game_t *p)
{
int n = p->n;
int nm1 = n - 1;
int yidx;
int xidx;
int xcur;
int xprev;
int *rowtop;
int *rowbot;
// check most rows
yidx = 0;
for (; yidx < nm1; ++yidx) {
// point to current row of board
rowtop = p->board[yidx];
// point to next row of board
rowbot = p->board[yidx + 1];
// get the "previous" value in the current row
xprev = rowtop[0];
// check all values in given row
for (xidx = 1; xidx < n; ++xidx, xprev = xcur) {
// get current value
xcur = rowtop[xidx];
// does it match the previous value in the row?
if (xcur == xprev)
return 1;
// check current value against value just below it in the next row
if (xcur == rowbot[xidx])
return 1;
}
}
// check last row
rowtop = p->board[yidx];
xprev = rowtop[0];
for (xidx = 1; xidx < n; ++xidx, xprev = xcur) {
xcur = rowtop[xidx];
if (xcur == xprev)
return 1;
}
return 0;
}
更新:
上述方法会起作用并且相当很快。
但是,我在速度方面“疯了”,所以,次要调整以最小化内存获取[稍微]:
typedef struct game {
int h;
int n;
int **board;
} game_t;
int
check(game_t *p)
{
int n = p->n;
int yidx;
int xidx;
int xcur;
int xprev;
const int *rowtop;
const int *rowbot;
// check most rows
rowtop = p->board[0];
for (yidx = 1; yidx < n; ++yidx, rowtop = rowbot) {
// point to next row of board
rowbot = p->board[yidx];
// get the "previous" value in the current row
xprev = rowtop[0];
// check all values in given row
for (xidx = 1; xidx < n; ++xidx, xprev = xcur) {
// get current value
xcur = rowtop[xidx];
// does it match the previous value in the row?
if (xcur == xprev)
return 1;
// check current value against value just below it in the next row
if (xcur == rowbot[xidx])
return 1;
}
}
// check last row
xprev = rowtop[0];
for (xidx = 1; xidx < n; ++xidx, xprev = xcur) {
xcur = rowtop[xidx];
if (xcur == xprev)
return 1;
}
return 0;
}