藍橋杯練習:青蛙跳杯子

青蛙跳杯子

原題鏈接:問題 1878: [藍橋杯][2017年第八屆真題]青蛙跳杯子
解題思路:將問題簡單轉化爲青蛙和*的換位,使用BFS搜索即可,爲避免重複狀態使用map存儲,可以在O(1)判重

import java.util.*;
public class Main {
    static class Fron {
        String now;
        int step;
        int pos;

        Fron(String now, int step, int pos) {
            this.now = now;
            this.pos = pos;
            this.step = step;
        }
    }

    static String start, end;
    static Queue<Fron> q = new ArrayDeque<Fron>();
    static Map<String, Integer> m = new HashMap<String, Integer>();
    static int[] dir = {-3, -2, -1, 1, 2, 3};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        start = sc.nextLine();
        end = sc.nextLine();
        int pos = 0;
        for (int i = 0; i < start.length(); i++) {
            if ('*' == start.charAt(i)) {
                pos = i;
                break;
            }
        }
        System.out.println(bfs(start, 0, pos));
        sc.close();
    }

    private static int bfs(String now, int step, int pos) {
        Fron f = new Fron(now, step, pos);
        q.offer(f);
        while (!q.isEmpty()) {
            Fron status = q.poll();
            if (status.now.equals(end)) {
                return status.step;
            }
            if (m.containsKey(status.now)) {
                continue;//重複狀態剪枝
            } else {
                m.put(status.now, 1);//非重複狀態存儲
            }
            for (int i = 0; i < 6; i++) {//搜尋六種跳法,即空位的6種交換
                int ind = status.pos + dir[i];//交換後的位置
                if (ind > -1 && ind < start.length()) {
                    String temp = swap(status.pos, ind, status.now);//交換後的狀態
                    Fron fNext = new Fron(temp, status.step + 1, ind);
                    if (!m.containsKey(temp)) {//重複狀態剪枝
                        q.offer(fNext);
                    }
                }
            }
        }
        return -1;
    }

    private static String swap(int pos, int ind, String now) {
        char[] c = now.toCharArray();
        char temp = c[pos];
        c[pos] = c[ind];
        c[ind] = temp;
        return new String(c);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章