北京林业大学“计蒜客”杯程序设计竞赛 网络赛 马踏棋盘的问题

来源:互联网 发布:侠盗飞车5mac版 编辑:程序博客网 时间:2024/05/22 08:05
//使用bfs#include<stdio.h>#include<iostream>#include<utility>#include<queue>#include<string.h>using namespace std;char a[100][100];int d[100][100]; //存放从起点开始到达每个点所用步数 ,同时也可标记该点有没有走过 int n, m;int dx[] = {-1,-2,-2, -1, 1, 2, 2, 1};int dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};int sx, sy;int rx, ry;typedef pair<int , int> P;int bfs();int isOk(int x, int y); int isOk(int x, int y){    if((x >= 0 && x < n) &&(y >= 0 && y < m) && d[x][y] == -1 && a[x][y] != '#')        return 1;    return 0;}int bfs(){    queue<P> que;    int i;    que.push(P(sx, sy));    d[sx][sy] = 0;    //不断循环直到队列的长度为零    while(que.size())    {        int nx, ny;        P p = que.front(); que.pop();    //  printf("出栈(%d,%d)\n", p.first, p.second);        if(a[p.first][p.second] == 'e')        {            break;        }        for(i = 0; i < 8; i++)        {            nx = p.first + dx[i];            ny = p.second + dy[i];        //  printf("%d, %d\n", nx, ny);                 if(isOk(nx, ny))                {                       if((i == 1 || i == 2) && a[p.first-1][p.second] == '#')                    continue;                else if((i == 3 || i == 4) && a[p.first][p.second+1] == '#')                    continue;                else if((i == 5 || i == 6) && a[p.first+1][p.second] == '#')                    continue;                else if((i == 7 || i == 0) && a[p.first][p.second-1] == '#')                    continue;                que.push(P(nx, ny));                if(nx == 1 && ny == 0 )                {                    printf("i = %d, %c\n", i, a[nx][ny-1]);                }                printf("入栈(%d,%d)\n", nx, ny);                d[nx][ny] = d[p.first][p.second]+1;            }           }    }     return d[rx][ry]; }int main(void){    sx = 0;    sy = 0;    int i = 0, j =0 ;    while(scanf("%d%d", &n, &m) != EOF)    {        getchar();        for(i = 0; i < n; i++)        {            for(j = 0; j <m; j++)            {                a[i][j] = getchar();            }            getchar();        }        rx = n-1; ry = m-1;        memset(d, -1, sizeof(d));        d[sx][sy] = 0;        int res = bfs();        printf("%d\n", res);            }    return 0;}
0 0