八数码难题 codevs1225 a*

3 篇文章 0 订阅

Description


Yours和zero在研究A*启发式算法.拿到一道经典的A*问题,但是他们不会做,请你帮他们.
问题描述

在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了使题目简单,设目标状态为123804765),找到一种最少步骤的移动方法,实现从初始布局到目标布局的转变。

Solution


八数码问题,题意日常裸
为了显示出些进步,我们用启发式搜索A*解决这一题
关键就在于估价函数。这里我们用所有数字错位的欧拉距离之和作为f,然后一串字符串可以拆成3*3的矩阵处理移动,又压回1*9的字符串。为了去重这里直接用stl的map了
经常性打错重载比较符,想死

Code


#include <iostream>
#include <string>
#include <queue>
#include <cmath>
#include <map>
#define rep(i, st, ed) for (int i = st; i <= ed; i += 1)
#define L 9
using std:: string;
struct data{
    string s;
    int f, g;
    bool operator <(data b)const{
        data a = *this;
        return a.f > b.f;
    }
};
struct pos{
    int x, y;
    pos operator +(pos b)const{
        pos a = *this;
        return (pos){a.x + b.x, a.y + b.y};
    }
}dir[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int rc[L][L];
inline int cmp(string a, string b){
    int tot = 0;
    rep(i, '0', '8'){
        tot += rc[a.find(i)][b.find(i)];
    }
    return tot;
}
inline void swap(char &a, char &b){
    char c = a;
    a = b;
    b = c;
}
using std:: priority_queue;
priority_queue<data>heap;
using std:: map;
map<string, bool> hash;
using std:: cout;
using std:: endl;
inline int bfs(string st, string ed){
    heap.push((data){st, cmp(st, ed), 0});
    hash[st] = true;
    while (!heap.empty()){
        data now = heap.top(); heap.pop();
        // cout << now.s << endl;
        if (now.s == ed){
            return now.g;
        }
        int p = now.s.find('0');
        int x = p / 3;
        int y = p % 3;
        pos nowPos = (pos){x, y};
        rep(k, 0, 3){
            pos tarPos = nowPos + dir[k];
            if (tarPos.x >= 0 && tarPos.x < 3 && tarPos.y >= 0 && tarPos.y < 3){
                string tar = now.s;
                swap(tar[nowPos.x * 3 + nowPos.y], tar[tarPos.x * 3 + tarPos.y]);
                if (hash[tar] == false){
                    hash[tar] = true;
                    heap.push((data){tar, now.g + 1 + cmp(tar, ed), now.g + 1});
                }
            }
        }
    }
}
using std:: cin;
using std:: abs;
int main(void){
    std:: ios:: sync_with_stdio(false);
    /*
    string a, b;
    cin >> a >> b;
    cout << cmp(a, b) << endl;
    return 0;
    */
    rep(i, 0, 2){
        rep(j, 0, 2){
            rep(k, 0, 2){
                rep(l, 0, 2){
                    rc[i * 3 + j][k * 3 + l] = abs(i - k) + abs(j - l);
                }
            }
        }
    }
    string st;
    cin >> st;
    string ed;
    ed = "123804765";
    int ans = bfs(st, ed);
    cout << ans << endl;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是用A*算法实现八数码难题的伪代码: ``` function Astar_Search(initial_state, goal_state): open_list = [initial_state] // 开放列表,初始状态加入其中 closed_list = [] // 封闭列表,不包含初始状态 g_score = {} // g值,表示从初始状态到当前状态的代价 g_score[initial_state] = 0 // 初始状态的代价为0 f_score = {} // f值,表示从初始状态到目标状态的估计代价 f_score[initial_state] = heuristic(initial_state, goal_state) // 初始状态的估计代价 parent = {} // 父节点,用于回溯 while open_list is not empty: current = state in open_list with the lowest f_score // 从开放列表中选取f值最小的状态 open_list.remove(current) closed_list.append(current) if current == goal_state: // 找到目标状态,回溯路径 path = [] while current in parent: path.append(current) current = parent[current] path.append(initial_state) path.reverse() return path for neighbor in get_neighbors(current): // 扩展当前状态的邻居节点 if neighbor in closed_list: continue // 跳过封闭列表中的节点 tentative_g_score = g_score[current] + 1 // 计算邻居节点的代价,每次移动一个数字或空格算作一步 if neighbor not in open_list or tentative_g_score < g_score[neighbor]: parent[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal_state) if neighbor not in open_list: open_list.append(neighbor) // 加入开放列表,如果邻居节点不在开放列表中 return [] // 无解 function heuristic(state, goal_state): // 启发函数,计算从当前状态到目标状态的估计代价,使用曼哈顿距离 distance = 0 for i in range(1, 9): current_pos = get_position(state, i) goal_pos = get_position(goal_state, i) distance += abs(current_pos[0] - goal_pos[0]) + abs(current_pos[1] - goal_pos[1]) return distance function get_position(state, value): // 获取数字value在状态state中的位置 for i in range(3): for j in range(3): if state[i][j] == value: return (i, j) function get_neighbors(state): // 获取当前状态的邻居节点 neighbors = [] empty_pos = get_position(state, 0) for move in [(0, -1), (-1, 0), (0, 1), (1, 0)]: new_pos = (empty_pos[0] + move[0], empty_pos[1] + move[1]) if 0 <= new_pos[0] < 3 and 0 <= new_pos[1] < 3: new_state = swap(state, empty_pos, new_pos) neighbors.append(new_state) return neighbors function swap(state, pos1, pos2): // 交换状态state中位置pos1和位置pos2上的数字或空格 new_state = [row[:] for row in state] new_state[pos1[0]][pos1[1]] = state[pos2[0]][pos2[1]] new_state[pos2[0]][pos2[1]] = state[pos1[0]][pos1[1]] return new_state ``` 在实现A*算法时,需要注意以下几点: 1. 需要使用优先队列来维护开放列表,确保每次选取f值最小的状态进行扩展。 2. 启发函数和代价函数的设计很关键,可以影响算法的效率和正确性。对于八数码难题,可以使用曼哈顿距离作为启发函数,每次移动一个数字或空格算作一步。 3. 在计算估计代价时,需要使用从起始状态到当前状态的代价加上从当前状态到目标状态的启发函数值。 4. 通过回溯,可以找到从起始状态到目标状态的最优路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值