Day11 HDUOJ2612广度优先搜索求最小路径
Posted cc的心理活动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Day11 HDUOJ2612广度优先搜索求最小路径相关的知识,希望对你有一定的参考价值。
//hduoj 2612
/*
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
*/
using namespace std;
int n,m;
char a[M][M];
bool visited[M][M];
int dist[M][M];
struct p {
int row;
int list;
int dist;
};
void BFS(queue<p> Q) {
int kfcnum = 0;
memset(visited, false, M * M * sizeof(bool));
int d[M][M];
while (!Q.empty()) {
p t = Q.front();
Q.pop();
if (a[t.row][t.list] == '@')
dist[t.row][t.list] += t.dist;
if (t.list < m&&!visited[t.row][t.list+1]&&a[t.row][t.list+1]!='#') {
p rt;
rt.row = t.row;
rt.list = t.list + 1;
rt.dist = t.dist + 1;
Q.push(rt);
visited[t.row][t.list+1] = true;
}
if (t.row < n && !visited[t.row+1][t.list] && a[t.row+1][t.list] != '#') {
p und;
und.row = t.row+1;
und.list = t.list;
und.dist = t.dist + 1;
Q.push(und);
visited[t.row+1][t.list] = true;
}
if (t.list >0 && !visited[t.row][t.list - 1] && a[t.row][t.list - 1] != '#') {
p lf;
lf.row = t.row;
lf.list = t.list - 1;
lf.dist = t.dist + 1;
Q.push(lf);
visited[t.row][t.list-1] = true;
}
if (t.row>0 && !visited[t.row-1][t.list] && a[t.row-1][t.list] != '#') {
p up;
up.row = t.row-1;
up.list = t.list;
up.dist = t.dist + 1;
Q.push(up);
visited[t.row-1][t.list] = true;
}
}
}
int main() {
while (cin >> n) {
memset(dist, 0, M * M * sizeof(int));
int numkfc = 0;
queue<p> Qy;
queue<p> Qm;
cin >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
for(int i=0;i<n;i++)
for (int j = 0; j < m; j++) {
if (a[i][j] == '@')
numkfc++;
if (a[i][j] == 'Y') {
p y;
y.dist = 0;
y.row = i;
y.list = j;
Qy.push(y);
}
if (a[i][j] == 'M') {
p ml;
ml.dist = 0;
ml.row = i;
ml.list = j;
Qm.push(ml);
}
}
BFS(Qy);
BFS(Qm);
/*for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cout << dist[i][j];
cout << endl;
}*/
int min = 10000;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (dist[i][j] != 0 && dist[i][j] < min)
min=dist[i][j];
cout << min * 11 << endl;
}
}
利用广度优先搜索可以实现单源最短路径计算,类似填表的思想每次遍历都在距离上加一。
以上是关于Day11 HDUOJ2612广度优先搜索求最小路径的主要内容,如果未能解决你的问题,请参考以下文章