1. 程式人生 > >廣度優先搜尋(8數碼問題)

廣度優先搜尋(8數碼問題)

#include <iostream>
#include <vector>
#include <limits>
#include <string>
#include<set>       
#include<queue>
using namespace std;


set<string> in_que; //用set來看當前的圖是否入過佇列
struct pos{
int x;
int y;


};
struct node{
string s_map;
struct pos pos_zero;
int dist;       //為了知道是第幾層
int parent;     //為了知道操作變換過程


};


queue<struct node> q;
int num_cnt = -1;      //標記當前元素的標號
int map_init[3][3] = { { 2, 8, 3 }, { 1, 6, 4 }, { 7, 0, 5 } };
int map_target[3][3] = { { 1, 2, 3 }, { 8, 0, 4 }, { 7, 6, 5 } };\
//     左        右         上         下
struct pos dirc[4] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
string s_map_tar;
vector<struct node> map_op_course;
int map_ele[3][3];




string code_map(int map[3][3], int row, int col)   //row i y代表行 col j x代表列
{
string s;
for (int i = 0; i <row; i++)
for (int j = 0; j < col; j++)
{
s += map[i][j] + '0';


}
return s;
}


void swap_map(char &x, char &y)
{
char temp;
temp = x;
x = y;
y = temp;


}
void show_dirct(string &str)
{
string substr;
for (int i = 0; i < 3; i++)
{
substr = str.substr(i * 3, 3);
cout << substr << endl;


}
cout << endl;


}
void output(vector<struct node> &map_op_course, struct node& map_q_top)
{
vector<int> vec_index;
int index;

index = map_q_top.parent;
while (index != -1)
{
vec_index.push_back(index);
index = map_op_course[index].parent;
}
show_dirct(map_op_course[0].s_map);          //展示最初的狀態
for (int i = vec_index.size()-1; i--; i >= 0)
{
show_dirct(map_op_course[vec_index[i]].s_map);



}
show_dirct(map_q_top.s_map);             //展示最末尾的狀態
}






void BFS_8_map(void)
{
struct node map_ele;
struct node map_q_top;
struct pos pos_zero_new;
map_ele.s_map = code_map(map_init, 3, 3);
map_ele.pos_zero.x = 1;
map_ele.pos_zero.y = 2;
map_ele.dist = 0;
map_ele.parent = -1;


q.push(map_ele);
while (!q.empty())
{
map_q_top = q.front();   //得到隊首元素
in_que.insert(map_q_top.s_map);  //用set標誌已經進過隊列了
num_cnt++;                //計算當前是第幾個了 第一個出棧時是0 num_cnt的值是-1


map_op_course.push_back(map_q_top);  //將彈出的元素加入過程向量中


              
q.pop();
if (map_q_top.s_map == s_map_tar)
{
break;


}
else
{
for (int i = 0; i < 4; i++)
{
pos_zero_new.x = map_q_top.pos_zero.x + dirc[i].x;
pos_zero_new.y = map_q_top.pos_zero.y + dirc[i].y;
if (pos_zero_new.x >= 0 && pos_zero_new.x < 3 && pos_zero_new.y >= 0 && pos_zero_new.y < 3 && in_que.find(map_q_top.s_map) != in_que.end())
{

swap_map(map_q_top.s_map[map_q_top.pos_zero.y * 3 + map_q_top.pos_zero.x], map_q_top.s_map[pos_zero_new.y * 3 + pos_zero_new.x]);

map_ele.dist = map_q_top.dist + 1;
map_ele.pos_zero = pos_zero_new;
map_ele.s_map = map_q_top.s_map;
map_ele.parent = num_cnt;
q.push(map_ele);


swap_map(map_q_top.s_map[map_q_top.pos_zero.y * 3 + map_q_top.pos_zero.x], map_q_top.s_map[pos_zero_new.y * 3 + pos_zero_new.x]);






}





}








}


}


cout << map_q_top.dist << endl;
output(map_op_course, map_q_top);
}




int main(void)
{
s_map_tar = code_map(map_target, 3, 3);
BFS_8_map();




}