跳到正文

算法·理论

暑假第9节课总结

flaming_red_dragon约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年7月15日
收录
2026年7月17日
更新
2026年11月10日
篇幅
约 5 分钟

版本

  1. v1当前

广度优先搜索 (bfs)

广度优先搜索像在一个区间内水流动的轨迹一样搜索。

并且广度优先搜索保证能求出步数最少的路线。

模版

C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x;
	int y;
};
char c[50][50];
int n,m,st[50][50];//需要使用的变量。
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};//方向:上、下、左、右。
void bfs(int x,int y)
{
	queue<node>que;
	que.push({x,y});
	st[x][y]=1;
	while(que.size())
	{
		node tmp=que.front();
		que.pop();
		for(int i=0;i<=3;i++)
		{
			int tx=tmp.x+dx[i];
			int ty=tmp.y+dy[i];
			if(tx<1||tx>n||ty<1||ty>m)
			{
				continue;
			}
			if(c[tx][ty]!='#'&&st[tx][ty]==0)
			{
				st[tx][ty]=st[tmp.x][tmp.y]+1;
				que.push({tx,ty});
			}
		 } 
	} 
}
int main()
{
     //执行内容...
    return 0;
}

题目

1. T672751 走迷宫(讲解后完成)

本题就是让我们算出不能走 # 的情况下的最短距离。
无难点

2. T672724 gogogo出发咯 (无问题)

本题就是让我们算出不能走1的情况下的最短距离。
无难点

3. T672726 农夫与牛 (讲解后完成)

本题就是让我们算出最短距离。
这道题的难点:
1. 有负数情况,所以都有加500。

4. T672737 奶牛搬水 (无问题)

本题就是让我们算出要多少只奶牛。
这道题的难点:
1. 枚举牛棚、湖、巨大岩石。

5. P8628 [蓝桥杯 2015 国 AC] 穿越雷区(讲解后完成)

本题就是让我们将走完 + 号走 - 号,走完 - 号走 + 号。
这道题的难点:
1. 脱离题目的束缚将它想成只要不同就走。

6. P6207 [USACO06OCT] Cows on Skates G(讲解后完成)

这道题就是让我们把走过的路记录下来。
这道题的难点:
1. 我们把走过的路记录下来。
C++
#include<bits/stdc++.h>
using namespace std;
struct node
{
	int x;
	int y;
};
char c[150][150];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int st[150][150];
node pre[150][150];
int r,cc;
void bfs(int x,int y)
{
	queue<node>que;
	que.push({x,y});
	st[x][y]=1;
	while(que.size())
	{
		node tmp=que.front();
		que.pop();
		for(int i=0;i<=3;i++)
		{
			int tx=tmp.x+dx[i];
			int ty=tmp.y+dy[i];
			if(tx<1||tx>r||ty<1||ty>cc)
			{
				continue;
			}
			if(c[tx][ty]!='*'&&st[tx][ty]==0)
			{
				st[tx][ty]=1;
				pre[tx][ty]={tmp.x,tmp.y};
				que.push({tx,ty});
			}
		 } 
	} 
}
int main()
{
    cin>>r>>cc;
    for(int i=1;i<=r;i++)
    {
    	for(int j=1;j<=cc;j++)
    	{
    		cin>>c[i][j];
		}
	}
	bfs(1,1);
	stack<node>path;
	int x=r,y=cc;
	while(!(x==1&&y==1))
	{
		path.push({x,y});
		node p=pre[x][y];
		x=p.x;
		y=p.y;
	}
	path.push({1,1});
	while(path.size())
	{
		node tnp=path.top();
		cout<<tnp.x<<" "<<tnp.y<<endl;
		path.pop();
	}
    return 0;
}

中的

C++
if(tx<1||tx>r||ty<1||ty>cc)
{
	continue;
}

ty<1ty<1写成了ty<0ty<0。

7. P1747 好奇怪的游戏(讲解后完成)、

这道题就是让一个象棋中的马和一个象棋中的象走到一个地点需要几步。
这道题的难点:
1. 就在于方向定位。
2. 将一个bfsbfs巧妙的两遍。
原文