1. 程式人生 > 其它 >九章演算法 | 嗶哩嗶哩面試題:滑動拼圖II

九章演算法 | 嗶哩嗶哩面試題:滑動拼圖II

技術標籤:演算法javac++資料結構c語言

描述

在一個3x3的網格中,放著編號1到8的8塊板,以及一塊編號為0的空格。

一次移動可以把空格0與上下左右四鄰接之一的板子交換。

給定初始和目標的板子排布,返回到目標排布最少的移動次數。

如果不能從初始排布移動到目標排布,返回-1.


線上做題地址:

LintCode 領釦

樣例1

輸入: 
[ 
 [2,8,3], 
 [1,0,4], 
 [7,6,5] 
] 
[ 
 [1,2,3], 
 [8,0,4], 
 [7,6,5] 
] 
輸出: 
4 
 
解釋: 
[                 [ 
 [2,8,3],          [2,0,3], 
 [1,0,4],   -->    [1,8,4], 
 [7,6,5]           [7,6,5] 
]                 ] 
 
[                 [ 
 [2,0,3],          [0,2,3], 
 [1,8,4],   -->    [1,8,4], 
 [7,6,5]           [7,6,5] 
]                 ] 
 
[                 [ 
 [0,2,3],          [1,2,3], 
 [1,8,4],   -->    [0,8,4], 
 [7,6,5]           [7,6,5] 
]                 ] 
 
[                 [ 
 [1,2,3],          [1,2,3], 
 [0,8,4],   -->    [8,0,4], 
 [7,6,5]           [7,6,5] 
]                 ] 

樣例2

輸入: 
[[2,3,8],[7,0,5],[1,6,4]] 
[[1,2,3],[8,0,4],[7,6,5]] 
輸出: 
-1 

使用單向 BFS 演算法

public class Solution { 
    /** 
     * @param init_state: the initial state of chessboard 
     * @param final_state: the final state of chessboard 
     * @return: return an integer, denote the number of minimum moving 
*/ public int minMoveStep(int[][] init_state, int[][] final_state) { String source = matrixToString(init_state); String target = matrixToString(final_state); Queue<String> queue = new LinkedList<>(); Map<String, Integer> distance = new
HashMap<>(); queue.offer(source); distance.put(source, 0); while (!queue.isEmpty()) { String curt = queue.poll(); if (curt.equals(target)) { return distance.get(curt); } for (String next : getNext(curt)) { if (distance.containsKey(next)) { continue; } queue.offer(next); distance.put(next, distance.get(curt) + 1); } } return -1; } public String matrixToString(int[][] state) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sb.append(state[i][j]); } } return sb.toString(); } public List<String> getNext(String state) { List<String> states = new ArrayList<>(); int[] dx = {0, 1, -1, 0}; int[] dy = {1, 0, 0, -1}; int zeroIndex = state.indexOf('0'); int x = zeroIndex / 3; int y = zeroIndex % 3; for (int i = 0; i < 4; i++) { int x_ = x + dx[i]; int y_ = y + dy[i]; if (x_ < 0 || x_ >= 3 || y_ < 0 || y_ >= 3) { continue; } char[] chars = state.toCharArray(); chars[x * 3 + y] = chars[x_ * 3 + y_]; chars[x_ * 3 + y_] = '0'; states.add(new String(chars)); } return states; } }

使用雙向 BFS 演算法。可以把這份程式碼當模板背誦。

public class Solution { 
    /** 
     * @param init_state: the initial state of chessboard 
     * @param final_state: the final state of chessboard 
     * @return: return an integer, denote the number of minimum moving 
     */ 
    public int minMoveStep(int[][] init_state, int[][] final_state) { 
        String source = matrixToString(init_state); 
        String target = matrixToString(final_state); 
 
        if (source.equals(target)) { 
            return 0; 
        } 
 
        Queue<String> forwardQueue = new ArrayDeque<>(); 
        Set<String> forwardSet = new HashSet<>(); 
        forwardQueue.offer(source); 
        forwardSet.add(source); 
 
        Queue<String> backwardQueue = new ArrayDeque<>(); 
        Set<String> backwardSet = new HashSet<>(); 
        backwardQueue.offer(target); 
        backwardSet.add(target); 
 
        int steps = 0; 
        while (!forwardQueue.isEmpty() && !backwardQueue.isEmpty()) { 
            steps++; 
            if (extendQueue(forwardQueue, forwardSet, backwardSet)) { 
                return steps; 
            } 
 
            steps++; 
            if (extendQueue(backwardQueue, backwardSet, forwardSet)) { 
                return steps; 
            } 
        } 
 
        return -1; 
    } 
 
    private boolean extendQueue(Queue<String> queue, 
                                Set<String> set, 
                                Set<String> targetSet) { 
        int size = queue.size(); 
        for (int i = 0; i < size; i++) { 
            String curt = queue.poll(); 
            for (String next : getNext(curt)) { 
                if (set.contains(next)) { 
                    continue; 
                } 
                if (targetSet.contains(next)) { 
                    return true; 
                } 
                queue.offer(next); 
                set.add(next); 
            } 
        } 
        return false; 
    } 
 
    public String matrixToString(int[][] state) { 
        StringBuilder sb = new StringBuilder(); 
        for (int i = 0; i < 3; i++) { 
            for (int j = 0; j < 3; j++) { 
                sb.append(state[i][j]); 
            } 
        } 
        return sb.toString(); 
    } 
 
    public List<String> getNext(String state) { 
        List<String> states = new ArrayList<>(); 
        int[] dx = {0, 1, -1, 0}; 
        int[] dy = {1, 0, 0, -1}; 
 
        int zeroIndex = state.indexOf('0'); 
        int x = zeroIndex / 3; 
        int y = zeroIndex % 3; 
 
        for (int i = 0; i < 4; i++) { 
            int x_ = x + dx[i]; 
            int y_ = y + dy[i]; 
            if (x_ < 0 || x_ >= 3 || y_ < 0 || y_ >= 3) { 
                continue; 
            } 
 
            char[] chars = state.toCharArray(); 
            chars[x * 3 + y] = chars[x_ * 3 + y_]; 
            chars[x_ * 3 + y_] = '0'; 
            states.add(new String(chars)); 
        } 
 
        return states; 
    } 
} 

更多題解參考:九章演算法