您的位置:首页 > 其它

校园迷宫-rqnoj-195

2013-05-04 15:26 176 查看
和上面的八数码难题差不多,因为是求最优解,所以用队列,至于判重,把一个个坐标映射成一个整数。

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=2000+10;
int a[maxn][maxn];
int n,m;

struct state
{
int x,y;
int step;
};

state start,target;

queue<state> q;
map <int,int> hash;

void init()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
}

int gethash(state st)
{
return st.x*m+st.y;
}

void readdata()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
scanf("%d",&a[i][j]);

// printmap();
scanf("%d%d",&start.x,&start.y);
scanf("%d%d",&target.x,&target.y);
start.step=0;
q.push(start);
hash[gethash(start)]=1;
}

bool trytoinsert(state st)
{
int h=gethash(st);
if (hash[h]) return false;
hash[h]=1;
return true;
}

void check(state st)
{
if (gethash(st)==gethash(target))
{
printf("%d\n",st.step);
exit(0);
}
}

int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
void expand(state cur, state &st,int i)
{
memcpy(&st,&cur,sizeof(cur));
st.x+=dx[i];
st.y+=dy[i];
st.step++;
}

void work()
{
while (!q.empty())
{
state cur=q.front();
q.pop();
//printf("%d,%d,%d\n",cur.x,cur.y,cur.step);
for (int i=0;i<4;i++)
{
state st;
expand(cur,st,i);
if (a[st.x][st.y] || st.x<1 ||st.x>n ||st.y<1 || st.y>m) continue;
check(st);
if (trytoinsert(st)) q.push(st);
}
}
printf("No Answer!\n");
}

int main()
{
//init();
readdata();
work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: