Ekn*_*oes 2 java sliding-tile-puzzle
我正试图测试一个15拼图是否可以解决.我写了一个适用于大多数谜题的方法,但有些则没有.
例如,这个谜题可以通过两个动作(0,11),(0,12)来解决.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 11, 13, 14, 15, 12
Run Code Online (Sandbox Code Playgroud)
这是更好的可视化拼图:
1 2 3 4
5 6 7 8
9 10 0 11
13 14 15 12
Run Code Online (Sandbox Code Playgroud)
但这个拼图的奇数奇偶校验为3,所以不应该是可以解决的.
public boolean isSolvable(int[] puzzle)
{
int parity = 0;
for (int i = 0; i < puzzle.length; i++)
{
for (int j = i + 1; j < puzzle.length; j++)
{
if (puzzle[i] > puzzle[j] && puzzle[i] != 0 && puzzle[j] != 0)
{
parity++;
}
}
}
if (parity % 2 == 0)
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
小智 10
我发现这些条件需要检查任何N x N拼图,以确定它是否可以解决.
显然,由于你的空白磁贴在偶数行(从底部算起),奇偶校验是奇数,你的网格宽度是偶数,这个难题是可以解决的.
这是根据链接中的规则进行检查的算法:
public boolean isSolvable(int[] puzzle)
{
int parity = 0;
int gridWidth = (int) Math.sqrt(puzzle.length);
int row = 0; // the current row we are on
int blankRow = 0; // the row with the blank tile
for (int i = 0; i < puzzle.length; i++)
{
if (i % gridWidth == 0) { // advance to next row
row++;
}
if (puzzle[i] == 0) { // the blank tile
blankRow = row; // save the row on which encountered
continue;
}
for (int j = i + 1; j < puzzle.length; j++)
{
if (puzzle[i] > puzzle[j] && puzzle[j] != 0)
{
parity++;
}
}
}
if (gridWidth % 2 == 0) { // even grid
if (blankRow % 2 == 0) { // blank on odd row; counting from bottom
return parity % 2 == 0;
} else { // blank on even row; counting from bottom
return parity % 2 != 0;
}
} else { // odd grid
return parity % 2 == 0;
}
}
Run Code Online (Sandbox Code Playgroud)