例题一:走迷宫 link
思路:
这就是一个广搜的模板题,唯一讲一下,
输入的多个数字是连在一起的,
可以考虑用“%1d”一个一个输。
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 1005;
const int dx[6] = {
0, 0, 0, -1, 1};
const int dy[6] = {
0, -1, 1, 0, 0};
int n, mapp[N][N], sx, sy, tx, ty, dis[N][N], que[N * N + 10][2];
bool vis[N][N];
bool check(int x, int y)
{
if(x >= 1 && x <= n && y >= 1 && y <= n) return 1;
return 0;
}
void bfs()
{
int head = 0, tail = 1;
que[1][0] = sx, que[1][1] = sy, vis[sx][sy] = 1;
while(head < tail)
{
head++;
int x = que[head][0], y = que[head][1];
if(x == tx && y == ty) {
printf("%d\n", dis[x][y]); return ;}
for(int i = 1; i <= 4; i++)
{
int nx = x + dx[i], ny = y + dy[i];
if(check(nx, ny) && !mapp[nx][ny] && !vis[nx][ny])
{
vis[nx][ny] = 1;
dis[nx][ny] = dis[x][y] + 1;
que[++tail][0] = nx, que[tail][1] = ny;
}
}
}
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%1d", &mapp[i][j]);
scanf("%d%d%d%d", &sx, &sy, &tx, &ty);
bfs();
return 0;
}
例题二:山峰和山谷 link
思路:
理性理解一下题目,
山峰指中间高,四周低;
山谷指中间低,四周高;
考虑BFS,每次从一个未被访问过的点进行BFS,
若搜索到的点与开始点高度相同,并且未被访问,加入队列;
若搜索到的点与开始点高度不相同,根据上方的山峰山谷定义进行判断
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 1010;
const int dx[] = {
0, -1, -1, 0, 1, 1, 1, 0, -1};
const int dy[] = {
0, 0, 1, 1, 1, 0, -1, -1, -1};
int n, mapp[N][N], ans1, ans2, que[N * N][2];
bool vis[N][N];
bool check(int x, int y) {
return (x >= 1 && x <= n && y >= 1 && y <= n);}
void bfs(int sx, int sy)
{
int h = 0, t = 1, val = mapp[sx][sy];
que[1][0] = sx, que[1][1] = sy;
vis[sx][sy] = 1;
bool flag1 = 0, flag2 = 0;
while(h < t)
{
h++;
int x = que[h][0], y = que[h][1];
for(int i = 1; i <= 8; i++)
{
int nx = x +dx[i], ny = y +dy[i];
if(check(nx, ny))
{
if(mapp[nx][ny] == val)
{
if(!vis[nx][ny])
vis[nx][ny] = 1, que[++t][0] = nx, que[t][1] = ny;
}
else
{
if(mapp[nx][ny] < val) flag1 = 1;
if(mapp[nx][ny] > val) flag2 = 1;
}
}
}
}
if(!flag1 && !flag2) ans1++, ans2++;
if(flag1 && !flag2) ans1++;
if(!flag1 && flag2) ans2++;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d", &mapp[i][j]);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(!vis[i][j]) bfs(i, j);
printf("%d %d\n", ans1, ans2);
return 0;
}
例题三:立体推箱子link
思路:
注意到此题难处理的地方在于长方体的状态。是站的?横躺的?还是竖躺的?
我们考虑(x, y, t)表示长方体的状态。t=0表示站的,t=1表示横躺,t=2竖躺的.
记录最右边的点和最下面的点为(x,y),然后bfs即可。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int hx[5][5] = {
{
}, {
0, -1, 1, 0, 0}, {
0, -1