java - 检查 15 个谜题是否可解

标签 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

这是一个更直观的谜题:

1   2   3   4   

5   6   7   8   

9   10  0   11  

13  14  15  12  

但是这个谜题的奇偶校验为 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;
}

我做错了什么?

最佳答案

I found these需要检查任何 N x N 谜题的条件,以确定它是否可解。

显然,由于您的空白图 block 位于偶数行(从底部数起),奇偶校验为奇数,并且您的网格宽度为偶数,因此这个难题是可以解决的。

这是根据链接中的规则进行检查的算法:

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;
    }
}

关于java - 检查 15 个谜题是否可解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570344/

相关文章:

python-3.x - Python实现BFS解决8个难题需要很长时间才能找到解决方案

java - 在 Java 中使用数组创建滑动数字拼图板

java - 变量在 onComplete 方法中很好,但在外面它是 null

java - 使用 javax.xml.stream.XMLStreamReader 时如何启用非 IANA 编码

java - 集合的一对多查询

java - 接口(interface)和继承如何影响Java中类和对象之间的关系?

java - 抽象 Activity 导致 findViewById() 不起作用

javascript - 尝试使用左、右、上箭头键来实现 15 款益智游戏的移动