nyoj--58 最少步数

23 篇文章 0 订阅
6 篇文章 0 订阅

题解

BFS或者DFS最短路。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;

typedef pair<int, int> pii;
const int inf = 1 << 30;
int maze[9][9] = {
  {1,1,1,1,1,1,1,1,1},
  {1,0,0,1,0,0,1,0,1},
  {1,0,0,1,1,0,0,0,1},
  {1,0,1,0,1,1,0,1,1},
  {1,0,0,0,0,1,0,0,1},
  {1,1,0,1,0,1,0,0,1},
  {1,1,0,1,0,1,0,0,1},
  {1,1,0,1,0,0,0,0,1},
  {1,1,1,1,1,1,1,1,1}
};
int dir[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} };
int d[9][9];
int t, sx, sy, ex, ey;
int minstep = inf;

void bfs()
{
    for(int i = 0; i < 9; ++i)
        for(int j = 0; j < 9; ++j)
            d[i][j] = inf;
    queue<pii> Q;
    Q.push(make_pair(sx, sy));
    d[sx][sy] = 0;

    while(!Q.empty())
    {
        pii u = Q.front();
        Q.pop();
        if(u.first == ex && u.second == ey) break;
        for(int i = 0; i < 4; ++i)
        {
            int nx = u.first + dir[i][0], ny = u.second + dir[i][1];
            if(nx < 0 || nx > 8 || ny < 0 || ny > 8 || maze[nx][ny] || d[nx][ny] != inf) continue;
            d[nx][ny] = d[u.first][u.second] + 1;
            Q.push(make_pair(nx, ny));
        }
    }
    cout << d[ex][ey] << endl;
}

void dfs(int x, int y, int step)
{
    if(x == ex && y == ey){
        minstep = min(minstep, step);
        return;
    }
    for(int i = 0; i < 4; ++i)
    {
        int nx = x + dir[i][0], ny = y + dir[i][1];
        if(nx < 0 || ny > 8 || ny < 0 || ny > 8 || maze[nx][ny]) continue;
        maze[nx][ny] = 1;
        dfs(nx, ny, step + 1);
        maze[nx][ny] = 0;
    }
}

int main()
{
    for(cin >> t; t--; )
    {
        cin >> sx >> sy >> ex >> ey;
        //bfs();
        minstep = inf;
        dfs(sx, sy, 0);
        cout << minstep << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值