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

//使用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;

}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值