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<String, Integer> d = new HashMap<>();// 初始状态到达一个状态需要移动的步数
    static HashMap<String, Boolean> 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<String> 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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值