基本上,我正在创建一个拼图,您可以在其中交换拼图。我想确保在交换 2 个元素时,选择是有效的。
由于拼图只有9 block (3x3),我目前使用的代码是:
function valid_selection(p1, p2) {
if (p1 == 1 && (p2 == 2 || p2 == 4)) return true;
if (p1 == 2 && (p2 == 1 || p2 == 3 || p2 == 5)) return true;
if (p1 == 3 && (p2 == 2 || p2 == 6)) return true;
if (p1 == 4 && (p2 == 1 || p2 == 5 || p2 == 7)) return true;
if (p1 == 5 && (p2 == 2 || p2 == 4 || p2 == 6 || p2 == 8)) return true;
if (p1 == 6 && (p2 == 3 || p2 == 5 || p2 == 9)) return true;
if (p1 == 7 && (p2 == 4 || p2 == 8)) return true;
if (p1 == 8 && (p2 == 5 || p2 == 7 || p2 == 9)) return true;
if (p1 == 9 && (p2 == 6 || p2 == 8)) return true;
return false;
}
但是,我可以通过编程方式执行此操作吗?有人知道这样的算法吗?
感谢任何帮助。
最佳答案
假设你的矩阵有这样的位置:
1 2 3
4 5 6
7 8 9
您应该能够执行以下操作:
if ( abs(p2-p1) == 3 // test for vertical connectedness
|| ( abs(p2-p1) == 1 // test for horizontal connectedness
&& ( p1+p2 != 7 && p1+p2 != 13) ) ) // except for edge cases (3,4 and 6,7)
return true;
关于algorithm - 比较 3x3 矩阵的 2 个元素以查看元素 2 是否与元素 1 相邻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966399/