滑动拼图 Sliding Puzzle

2018-09-09 22:01:02

问题描述:

问题求解:

问题很Interesting,其实本质就是解空间遍历,使用BFS就可以很快的予以解决~

    public int slidingPuzzle(int[][] board) {
        String goal = "123450";
        String start = "";
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                start += (char)(board[i][j] + '0');
            }
        }
        HashSet<String> set = new HashSet<>();
        int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        set.add(start);
        Queue<String> q = new LinkedList<>();
        int step = 0;
        if (start.equals(goal)) return step;
        q.add(start);
        while (!q.isEmpty()) {
            step++;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                String cur = q.poll();
                int idx = cur.indexOf('0');
                int row = idx / 3;
                int col = idx % 3;
                for (int[] dir : dirs) {
                    int x = row + dir[0];
                    int y = col + dir[1];
                    if (x < 0 || x > 1 || y < 0 || y > 2) continue;
                    int idx2 = x * 3 + y;
                    StringBuffer sb = new StringBuffer(cur);
                    sb.setCharAt(idx, sb.charAt(idx2));
                    sb.setCharAt(idx2, '0');
                    String t = sb.toString();
                    if (t.equals(goal)) return step;
                    if (set.contains(t)) continue;
                    set.add(t);
                    q.add(t);
                }
            }
        }
        return -1;
    }
原文地址:https://www.cnblogs.com/hyserendipity/p/9615592.html