nyoj--58 最少步数

题解

BFS或者DFS最短路。

#include 
#include 
#include 
#include 
#include 
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 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;
}

你可能感兴趣的:(搜索,搜索--BFS,图论)