• 滑动拼图 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;
        }
    
  • 相关阅读:
    [LeetCode]Binary Tree Inorder Traversal
    [LeetCode]Binary Tree Preorder Traversal
    [LeetCode]Number of 1 Bits
    [LeetCode]Best Time to Buy and Sell Stock IV
    第四章 线程
    第三章 进程描述和控制
    第二章 操作系统概述
    第一章 计算机系统概述
    Qt创建对话框的三种方法
    strdup函数
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9615592.html
Copyright © 2020-2023  润新知