BFS- BFS(幅優先-検索)

どんなに高い山、登る、常に登る;
道路は、上に行く、長くなることが到達することができるようになります。

BFS- BFS(幅優先-検索)

ここに画像を挿入説明
まずは、特定の視覚化写真を幅優先探索であるかを理解することができます。距離条件ハフマンを考慮して、最短のソリューションは、クエリの中心半径として自分自身で始めることができ、特定のポイントに到達見つけます。これはBFSです。
次に、図GIFの論理図で表示するためのコードを
ここに画像を挿入説明
上記のように、全体的なロジックは、我々は、タスクを格納するために、(受信)を格納するために、アレイの決意を必要とします。
私たちは、キューの最初の要素は、もはやに行くことをされ、すべてのマーク1を通過することはできません、上を歩くようになったが、預金1の拡張の残り、最終目的地、BFSの後、最後に達した場合には
、私たちをキューはFIFOであるため、一定の秩序を確保するためにあなたは、キューを選択する必要があります。
私たちは、次のコードを描くことができます

#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<utility>
#include<stdio.h>
#include<vector>
#include<string>
#include<math.h>
#include<cmath>
#include<queue>
#include<stack>
#include<deque>
#include<map>
#pragma warning(disable:4244)
#define PI 3.1415926536
#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll ll_inf = 9223372036854775807;
const int int_inf = 2147483647;
const short short_inf = 32767;
const char char_inf = 127;
inline ll read() {
	ll c = getchar(), Nig = 1, x = 0;
	while (!isdigit(c) && c != '-')c = getchar();
	if (c == '-')Nig = -1, c = getchar();
	while (isdigit(c))x = ((x << 1) + (x << 3)) + (c ^ '0'), c = getchar();
	return Nig * x;
}
inline void out(ll a)
{
	if (a < 0)putchar('-'), a = -a;
	if (a >= 10)out(a / 10);
	putchar(a % 10 + '0');
}
ll qpow(ll x, ll n, ll mod) {
	ll res = 1;
	while (n > 0) {
		if (n & 1)res = (res * x) % mod;
		x = (x * x) % mod; n >>= 1;
	}
	return res;
}
#define read read()
int  n, m;
struct node {
	int x, y, step;
};
node temp;
bool judge[1000][1000];//判断数组,判断是否已经走过,或者是否可走
queue<node>q;
int dx[] = { 0,0,1,-1 };//简便行走上下左右
int dy[] = { 1,-1,0,0 };
void bfs()
{
	while (1)//一直走,知道无解或者有答案为止
	{
		if (q.empty())//如果已经走完全部的队列都没有结果就说明无解
		{
			cout << -1 << endl;
			return;
		}
		temp = q.front();//取任务
		q.pop();//删除任务
		judge[temp.x][temp.y] = 1;//该点已走过
		for (int i = 0; i < 4; i++)//四个方向都加队列
			if (!judge[temp.x + dx[i]][temp.y + dy[i]])//如果没有走过,可行就加
			{
				if (temp.x + dx[i] == n && temp.y + dy[i] == m)//如果当前走到了终点,就输出答案
				{
					cout << temp.step + 1 << endl;
					return;
				}
				q.push({ temp.x + dx[i], temp.y + dy[i], temp.step + 1 });//不是终点就入队列
			}
	}
}
int main()
{
	n = read, m = read;
	for (int i = 0; i <= n + 1; i++)judge[i][0] = judge[i][m + 1] = 1;//围墙
	for (int i = 0; i <= m + 1; i++)judge[0][i] = judge[n + 1][i] = 1;//围墙
	for (int i = 1; i <= n; i++)for (int j = 1; j <= m; j++)judge[i][j] = read;//接收数据
	q.push({ 1,1,1 });//入队列第一个元素
	bfs();
}

バイ・ホイール月

公開された32元の記事 ウォンの賞賛8 ビュー1168

おすすめ

転載: blog.csdn.net/qq_35339563/article/details/105027590