[每日一题2020.06.20]BFS

一道典型的BFS题

1592558606705

需要注意的是 :

  1. 记录路径, 采用记录上一个点是如何到这一个点 的方式 ( 前驱 )
  2. BFS求得的路一定是最短路, 因为采用的是层层扩展的方式

然后就是一些细节问题了

#include<vector>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;


#define debug(x) \
(void)(cerr << "L" << __LINE__\
			<< " : " << #x << " = " \
			<< (x) << endl )

void reIO() {
#ifndef ROCCOSHI
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
}

const int maxn = 100+ 5;
bool vis[maxn][maxn]; // 标记访问与否
int mp[maxn][maxn];	// 存图
int m = 5, n = 5;	// 5x5矩阵
int goes[maxn][maxn]; // 存路径

int dx[4] = {-1, 1, 0, 0}; // up down left right
int dy[4] = {0, 0, -1, 1}; // up down left right

struct h {
	int x, y;	// 节点
};

bool jdg(int x, int y) {
	return (x<0 || x >=5 || y < 0 || y >= 5 || vis[x][y] || mp[x][y]) ? 0 : 1; // 是否可到达
}

void printpath(h here) {
	stack< pair<int, int> > st;
	st.push(make_pair(here.x, here.y));
	h next;
	int dir = goes[here.x][here.y];
	next.x = here.x - dx[dir];
	next.y = here.y - dy[dir];

	while(next.x != 0 || next.y != 0) {

		int nx = next.x;
		int ny = next.y;
		debug(nx);
		debug(ny);
		debug(goes[nx][ny]);

		st.push(make_pair(next.x, next.y));
		dir = goes[next.x][next.y];
		next.x = next.x - dx[dir];
		next.y = next.y - dy[dir];
	}
	st.push(make_pair(0, 0));
	while(!st.empty()) {
		cout << '(' << st.top().first << ", " << st.top().second << ')' << endl;
		st.pop();
	}
}


void bfs() {
	queue<h> q;
	h newh;
	newh.x = 0;
	newh.y = 0;
	q.push(newh);
	vis[0][0] = 1;

	while(!q.empty()) {
		h here = q.front();
		q.pop();
		if (here.x == 4 && here.y == 4) { 
			printpath(here);
			return;
		}		
		for (int i = 0; i < 4; ++i)	// 上下左右查询
		{
			int xx = here.x + dx[i];
			int yy = here.y + dy[i];
			h newh;
			newh.x = xx;
			newh.y = yy;
			if (!jdg(xx, yy))
				continue;
			q.push(newh);
			debug(cnt);
			debug(xx);
			debug(yy);
			debug(i);
			vis[xx][yy]  = 1;
			goes[xx][yy] = i; // 上一个节点是怎么到我这来的?
		}
	}
}

int main() {
	cout.tie(0);
	cin.tie(0);

	reIO();
	for(int i = 0; i < n; ++i) {
		for(int j = 0; j < m; ++j) {
			cin >> mp[i][j];
		}
	}
	bfs();
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/roccoshi/p/13164358.html
今日推荐