【发布时间】:2019-01-17 20:29:32
【问题描述】:
下面是一个函数,旨在在一维向量中的相邻数字之间执行相等测试。
这个一维向量将具有代表 nxn 网格的值。 [ v 是向量]
当它们相等时返回 false。
例如考虑这个 3x3 网格:
i\j| 0 | 1 | 2
0 | 1 | 2 | 3
1 | 4 | 5 | 6
2 | 7 | 8 | 9
我编写的代码的问题是,并非网格中的所有数字都会有 4 个其他相邻数字并测试不存在的索引,例如在尝试比较网格中左上角数字上方的数字时(示例中的 1)可能会导致一些不准确的结果。
除此之外,我写的似乎不是最有效的方法。肯定有比列出 5 个新变量更简单的方法吗?
for( int i= 0; i < n ; i++ ){
for( int j = 0; j < n; j++){
int x = v[convert(i, j, n)];
int c = v[convert(i-1, j, n)];
int s = v[convert(i+1, j, n)];
int b = v[convert(i, j+1, n)];
int n = v[convert(i, j-1, n)];
if (x == c || x == s || x == b || x == n ) {
return false;
}
}
}
//another function used to convert 2d into 1D index
int convert(int row, int col, int rowlen){
return row*rowlen+col;
}
我将不胜感激。
【问题讨论】:
-
一般情况下,避免绑定检查的另一种方法是用“哨兵”包围阵列(将 3x3 阵列转换为 5x5 阵列),并在阵列的“中心”正常工作。
标签: c++ for-loop if-statement vector