四子连棋

来源:互联网 发布:修真的电脑程序员txt 编辑:程序博客网 时间:2024/06/08 00:40
#include<stdio.h>#include<stdlib.h>#include<queue>#include<map>#include <stdio.h>#include <string.h>#include<iostream>#include <fstream>using namespace std;struct status{    int hash,step,last;    int map[6][6];};const int dx[]={1, -1, 0, 0};                 //初始化可移动的方向const int dy[]={0, 0, 1, -1};bool hash[40700017];status first;queue<status>Q;int gethash(status a)                   //把此时棋盘的状态(全部用0,1,2表示没一位的三进制)转换成一个十进制数,用来哈希查找。{int res = 0;int k = 1;int i, j;for (i = 4; i >= 1; i--)for (j = 1; j <= 4; j++){res += a.map[i][j] * k;k *= 3;}return res% 40700017;}bool check(status a)       //判断,此时的棋盘状态是否已经是目标状态了。{int i, j;for (i = 1; i <= 4; i++)       //横向连成4个{bool flag = true;for (j = 2; j <= 4; j++)if(a.map[i][j-1] != a.map[i][j])flag = false;if (flag)    return true;}for (i = 1;i <= 4; i++)      //纵向连成4个 {   bool flag = true;for (j = 2; j <= 4; j++)if(a.map[j][i] != a.map[j-1][i])flag = false;if (flag)    return true;}if (a.map[1][1] == a.map[2][2])      //对角线if (a.map[2][2] == a.map[3][3])if (a.map[3][3] == a.map[4][4])return true;if (a.map[1][4] == a.map[2][3])      //对角线if (a.map[2][3] == a.map[3][2])if (a.map[3][2] == a.map[4][1])return true;    //cout<<"fuck";return false;}int swap(int &a,int &b){    int t;    t=a;    a=b;    b=t;}void move(status now,int x1,int y1,int k){    //新的坐标 x1+dx[k],y1+dy[k],看是否越界    //函数完成,如果x1,y1, 比较一下hash,看一下是不是上一步走过的。    status temp=now;    int num;    int newx=x1+dx[k],newy=y1+dy[k];    if(newx<1||newx>4)return;    if(newy<1||newy>4)return;    if(now.map[newx][newy]==now.last)return;    temp.last=3-temp.last;    temp.step++;    swap(temp.map[newx][newy],temp.map[x1][y1]);    num=gethash(temp);    if(hash[num]==0){        hash[num]=1;        Q.push(temp);    }}void bfs(){first.hash = gethash(first);     //首状态对应的十进制数first.last = 1;                  //因为谁先下都行。 所以开始要进队两个元素。 注意 first.last 是不同的。Q.push(first);first.last = 2;Q.push(first);while (!Q.empty()){status now;now= Q.front();Q.pop();cout<<now.step<<" ";if(check(now)){cout<<now.step;return;}int x1 = -1, x2 = -1, y1 = -1, y2 = -1;int i, j, k;for (i = 1; i <= 4; i++) for (j = 1; j <= 4; j++)            //寻找两个空格的坐标if (!now.map[i][j]){ if (x1 == -1 && y1 == -1)         //x1,y1; x2,y2 分别是两个空格的坐标{x1 = i;y1 = j;}else{x2 = i;y2 = j;}}for (k = 0; k < 4; k++)      //一个棋盘有两个空格,所以两个一起来搜索四个方向。{move(now, x1, y1, k); move(now, x2, y2, k);}}}int main(){    ifstream cin("ha.txt");int i, j;memset(first.map,0,sizeof(first.map));memset(hash,0,sizeof(hash));  for (i = 1; i <= 4; i++){char s[10];cin>>s;for (j = 0; j < 4; j++)          //把每一位的棋子换成 0(空格),1(黑子),2(白子) (三进制) ,此时棋盘的每个格子都是0,1,2.的数字{                          //这是一个16位的3进制数,对应一个十进制数。然后通过哈希该棋盘的十进制数 就可以找到对应的棋盘状态。if (s[j] == 'B') first.map[i][j+1] = 1;if (s[j] == 'W') first.map[i][j+1] = 2;}}first.step=0;bfs();return 0;}

0 0
原创粉丝点击