您的位置:首页 > 其它

nyoj--58 最少步数

2016-03-19 10:21 330 查看

题解

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nyoj 图论 dfs bfs easy