poj_1915 knight moves

题目地址:http://poj.org/problem?id=1915

题目大意:给定棋盘规格和起始点和目的点,计算出走日字的马从起始到目的的最少步数

how:简单的广度优先搜索,将某个点能去的所有的地方全部入队列,并将到达某个点的所用步数用代表整个棋盘的数组记录下来,最后输出的时候直接访问下标就行了

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<queue>
using namespace std;
int ma[500][500],flag[500][500];
int dx[]={1,1,-1,-1,2,2,-2,-2};
int dy[]={2,-2,2,-2,1,-1,1,-1};//八个方向的走法
int sx,sy,ex,ey,n;

/*struct po{
int x,y;
};*/


void bfs(){
//po poi,_poi,vpoi;
int vx,vy,zx,zy;
queue <int> q;
memset(ma,0,sizeof(ma));
memset(flag,0,sizeof(flag));

flag[sx][sy]=1;
vx=sx;
vy=sy;
q.push(vx);
q.push(vy);
while(!q.empty()){
    vx = q.front();q.pop();
    vy = q.front();q.pop();
    if(vx==ex&&vy==ey) break;//弹出条件

    for(int i=0;i<8;i++)
    {
        zx=vx+dx[i];
        zy = vy+dy[i];   

        if(!flag[zx][zy]&& zx>=0 && zx<n && zy>=0 && zy<n){//判断该点是否可走,若是则标记访问过且将其入队列并计算棋盘数组中的步数
            q.push(zx);
            q.push(zy);
            flag[zx][zy]=1;
            ma[zx][zy]=ma[vx][vy]+1;

        }
    }

}

}

int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        cin>>sx>>sy>>ex>>ey;
        bfs();
        cout<<ma[ex][ey]<<endl;
    }
}

这个程序我尝试了用结构体的方法去做,但是似乎会在运行的过程中报爆内存的错误,先把代码贴在这儿,引以为鉴。。。。

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<queue>
using namespace std;
int ma[500][500],flag[500][500];
int dx[]={1,1,-1,-1,2,2,-2,-2};
int dy[]={2,-2,2,-2,1,-1,1,-1};
int sx,sy,ex,ey,n;

struct po{
int x,y;
};


void bfs(){
po poi,_poi,vpoi;
queue <po> q;
memset(ma,0,sizeof(ma));
memset(flag,0,sizeof(flag));

flag[sx][sy]=1;
poi.x=sx;
poi.y=sy;
q.push(poi);
while(!q.empty()){
    vpoi = q.front();q.pop();
    if(vpoi.x==ex&&vpoi.y==ey) break;

    for(int i=0;i<8;i++)
    {
        _poi.x=vpoi.x+dx[i];
        _poi.y = vpoi.y+dy[i];   //_poi.x<n && _poi.x>=0 && _poi.y>=0 && _poi.y<n

        if(!flag[_poi.x][_poi.y]&& _poi.x>=0 && _poi.x<n && _poi.y>=0 && _poi.y<n){
            q.push(_poi);
            flag[_poi.x][poi.y]=1;
            ma[_poi.x][_poi.y]=ma[vpoi.x][vpoi.y]+1;

        }
    }

}

}

int main(){
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        cin>>sx>>sy>>ex>>ey;
        bfs();
        cout<<ma[ex][ey]<<endl;
    }
}

运行中发生的错误搞不懂啊。。。terminated called throwing.....什么什么的。。。。

原文地址:https://www.cnblogs.com/jokerspace/p/7085086.html