zoj1091_hdu1372_Knight Moves

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=91

http://acm.hdu.edu.cn/showproblem.php?pid=1372


BFS是自己写的,DFS是看别人的。


代码:

#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
using namespace std;

const int dx[] = {1, 1, 2, 2, -2, -2, -1, -1};
const int dy[] = {2, -2, 1, -1, 1, -1, 2, -2};
const int N = 10;
char ch1, ch2, ch3, ch4;
int x1, y1, x2, y2;
int visited[N][N]; //used in bfs
int used[N][N];    //used in dfs

bool inside(int x, int y)
{
    return (0 <= x && x <= 7 && 0 <= y && y <= 7);
}

void bfs()
{
    queue<int> q;
    visited[x1][y1] = 1;
    q.push(x1);
    q.push(y1);
    int x, y;
    while (!q.empty())
    {
        x = q.front(), q.pop();
        y = q.front(), q.pop();
        if (x == x2 && y == y2)
        {
            printf("To get from %c%c to %c%c takes %d knight moves.\n", ch1, ch2, ch3, ch4, visited[x2][y2]-1);
            break;
        }
        for (int i = 0; i < 8; i++)
        {
            int tmpx = x + dx[i], tmpy = y + dy[i];
            if (inside(tmpx, tmpy) && !visited[tmpx][tmpy])
            {
                q.push(tmpx);
                q.push(tmpy);
                visited[tmpx][tmpy] = visited[x][y] + 1;
            }
        }
    }
}

void dfs(int x, int y, int t)
{
    if (!inside(x, y) || t >= used[x][y])  //剪枝
        return;
    used[x][y] = t;             //当不越界时,对地图进行松弛,将步数更新为当前最小
    for (int i = 0; i < 8; i++)
        dfs(x+dx[i], y+dy[i], t+1);
}

int main()
{
    //freopen("in", "r", stdin);
    while (scanf("%c%c %c%c\n", &ch1, &ch2, &ch3, &ch4) != EOF)
    {
        x1 = ch1 - 'a', y1 = ch2 - '1';
        x2 = ch3 - 'a', y2 = ch4 - '1';

//        memset(visited, 0, sizeof(visited));
//        bfs();

        for (int i = 0; i < 8; i++)
            for (int j = 0; j < 8; j++)
                used[i][j] = 64;
        dfs(x1, y1, 0);
        printf("To get from %c%c to %c%c takes %d knight moves.\n", ch1, ch2, ch3, ch4, used[x2][y2]);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值