栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

acwing 八数码:bfs+java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

acwing 八数码:bfs+java

题目:

思路:

使用bfs进行搜索,同时将二维的数组转为一维的字符串,将“x”在二维数组中的索引转换为一维字符串的索引,每一种字符串都是一个新的状态,当状态与“12345678x”相同时,则停止搜索。

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Shu_Zhi_Ma {
    static HashMap d = new HashMap<>();// 初始状态到达一个状态需要移动的步数
    static HashMap stu = new HashMap<>();// 该状态是否被已经加入
    static int[][] dir = new int[][]{{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
    char[][] path = new char[100][2];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String start = br.readLine().replace(" ", "");
        System.out.println(start);
        int ans = bfs(start);
        System.out.println(ans);
    }

    static int bfs(String start) {
        Queue q = new LinkedList<>();// 队列,存储的是字符串,
        q.offer(start);// 将初始状态加入队列
        d.put(start, 0);// 初始化

        while (q.size() != 0) {
            String t = q.poll();// 弹出队首字符串
            int x_address = t.indexOf("x");// “x”的一维地址
            int x_now = x_address / 3, y_now = x_address % 3;// “x”的二维地址

            if (t.equals("12345678x"))// 说明t已经到达了最终需要的状态,返回移动步数
                return d.get(t);
            stu.put(t, true);// 将该状态加入已访问集合

            for (int i = 0; i < 4; i++) {
                int x_temp_two = x_now + dir[i][0], y_temp_two = y_now + dir[i][1];// x_temp_two,y_temp_two是bfs向四周移动的位置的二维地址swap
                if (x_temp_two >= 0 && y_temp_two >= 0 && x_temp_two < 3 && y_temp_two < 3) {// 判断swap该位置是否合法
                    int x_swap = x_temp_two * 3 + y_temp_two;// 与”x“进行交换的字符swap在一维中的index
                    String t_temp = swap(t, x_address, x_swap);// 将wswap与“x”进行交换
                    if (stu.get(t_temp) == null) {// 若为null,则说明t_temp这是新的状态
                        q.offer(t_temp);
                        d.put(t_temp, d.get(t) + 1);
                    }
                }
            }
        }
        return -1;
    }

    static String swap(String s, int a, int b) {
        StringBuffer sb = new StringBuffer(s);
        char temp = sb.charAt(a);
        sb.setCharAt(a, sb.charAt(b));
        sb.setCharAt(b, temp);
        return sb.toString();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988554.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号