poj 1077 八数码 问题 BFS

递推式的时候一定要注意+号m+=m+n,左边的加号加不加

我查了半天啊

#include<stdio.h>
 #include<iostream>
 #include<string.h>
 #include<stdlib.h>
 #include<queue>
 #include<set>
 #include<stack>
#include <fstream>
 using namespace std;

#define max 8000003

struct node
{
	char state[3][3];
	int x,y;
	int pre;
	char opr;

}all[400000];

int hash[max];

queue<int> qe;

stack<char> st;

node head;

int dirx[4]={1,-1,0,0};

int diry[4]={0,0,1,-1};

int getHash(node n)
{
	int i,j;
	int sum=0;
	for(i=0;i<3;i++)
	{
		for(j=0;j<3;j++)
		{
			sum=sum*10+n.state[i][j]-'0';//注意左边没加号
		}
	}

	return sum%max;
}

void getpath(node m)
{
	while(m.pre!=-1)
	{
		st.push(m.opr);
		m=all[m.pre];
	}
}

void bfs()
{
	memset(hash,0,sizeof(hash));
	node outnode,newnode;

	int hashvalue;

	int curent=0,isok=0,i;

	all[curent]=head;
	hash[getHash(head)]=1;
	qe.push(curent);
	curent++;

	while(!qe.empty())
	{
		
		int index=qe.front();
		outnode=all[index];
		qe.pop();

		if(getHash(outnode)==3456735)
		{
			isok=1;
			break;
		}

		int x=all[index].x;
		int y=all[index].y;

	//	printf("%d %d %d\n",qe.size(),x,y);

		for(i=0;i<4;i++)
		{
			int newx=x+dirx[i];
			int newy=y+diry[i];

			if(newx<0||newx>2||newy<0||newy>2)continue;

			newnode=outnode;

			swap(newnode.state[x][y],newnode.state[newx][newy]);

			hashvalue=getHash(newnode);
			if(hash[hashvalue])continue;
			hash[hashvalue]=1;

			newnode.x=newx;
			newnode.y=newy;
			newnode.pre=index;

			if(dirx[i]==0)
			{
				if(diry[i]==1)newnode.opr='r';
				else newnode.opr='l';
			}

			if(diry[i]==0)
			{
				if(dirx[i]==1)newnode.opr='d';
				else newnode.opr='u';
			}

			qe.push(curent);
			all[curent++]=newnode;

		}

	}

	if(!isok)
	{
		printf("unsolvable\n");
		return ;
	}

	getpath(outnode);

	while(!st.empty())
	{
		printf("%c",st.top());
		st.pop();
	}
	printf("\n");
}

int main(void)
{
     int i,j;

	 //ifstream cin("input.txt");

	 for(i=0;i<3;i++)
	 {
		 for(j=0;j<3;j++)
		 {
			cin>>head.state[i][j];
			if(head.state[i][j]=='x')
			{
				head.x=i;
				head.y=j;
				head.state[i][j]='0';
			}
		 }
	 }

	 head.pre=-1;
	 head.opr='0';
     
     bfs();

     return 0;
}

  

posted @ 2012-04-01 08:55  shijiwomen  阅读(314)  评论(0编辑  收藏  举报