广度优先搜索
以UOJ上的骑士游历为例
传送门
struct note {
int x;
int y;
int s;
} que[2501];
que[tail].x = 1; //x坐标
que[tail].y = 1; //y坐标
que[tail].s = 0; //记录步数
tail++;
b[1][1] = 1; //标记数组
while(head < tail) { //如果所有的都被走过了 head == tail
for(int i = 0; i<4; i++) {
tx = que[head].x + next[i][0]; //尝试4个方向
ty = que[head].y + next[i][1];
if(tx > n || tx < 1 || ty > m || ty < 1) {
continue;
}
if(!b[tx][ty]) {
b[tx][ty] = 1;
que[tail].x = tx; //将新的扩张点插入队尾
que[tail].y = ty;
que[tail].s = que[head].s+1; //到达该点的步数为前驱的步数+1
tail++; //尾指针++
}
if(tx == n && ty == m) { //判断是否到达目标点
judge = 1;
break;
}
}
if(judge) {
break;
}
head++; //头指针一定要++
}
令我印象深刻的一道广搜。
第一次,没有反应过来,有100000组询问,而我第一次每次询问都去广搜了一遍,结果70分。
第二次,请教了学长,发现从任意一点出发,与从那一点出发能到达的所有点中的任意一点出发,能到达的格数是一样的,据说这叫连通块。所以只用广搜一次,从每个未被访问过的点出发,直到遍历完全图。据说这叫“预处理”。代码没有体现面向对象的原则……
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct node {
int x;
int y;
int s;
node() {
x = 0;
y = 0;
s = 0;
}
} que[1000000];
int map[1001][1001],b[1001][1001];
int n,m;
int read_In() {
int a = 0;
bool minus = false;
char ch = getchar();
while (!(ch == '-' || (ch >= '0' && ch <= '9'))) ch = getchar();
if (ch == '-') {
minus = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
a = a * 10 + (ch - '0');
ch = getchar();
}
if (minus) a = -a;
return a;
}
void printOut(int x) {
char buffer[20];
int length = 0;
bool minus = x < 0;
if (minus) x = -x;
do {
buffer[length++] = x % 10 + '0';
x /= 10;
} while (x);
if (minus) buffer[length++] = '-';
do {
putchar(buffer[--length]);
} while (length);
putchar('\n');
}
void bfs(int start_X,int start_Y) {
const int next[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
int head = 0,tail = 0;
b[start_X][start_Y] = 1;
que[tail].x = start_X;
que[tail].y = start_Y;
que[tail].s = map[start_X][start_Y];
tail++;
int tx,ty;
while(head < tail) {
for(int i = 0; i<4; i++) {
tx = que[head].x + next[i][0];
ty = que[head].y + next[i][1];
if(tx > n || ty > n || tx < 1 || ty < 1) {
continue;
}
if(!b[tx][ty] && map[tx][ty] + que[head].s == 1) {
b[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tail].s = map[tx][ty];
tail++;
}
}
head++;
}
for(int i = 0; i<tail; i++) {
b[que[i].x][que[i].y] = tail;
}
}
int main() {
n = read_In();
m = read_In();
for(int i = 1; i<=n; i++) {
for(int j = 1; j<=n; j++) {
char ch = getchar();
while (!(ch >= '0' && ch <= '1')) ch = getchar();
map[i][j] = ch - '0';
}
}
for(int i = 1; i<=n; i++) {
for(int j = 1; j<=n; j++) {
if(b[i][j]){
continue;
}
if(!b[i][j]) {
bfs(i,j);
}
}
}
for(int i = 1; i<=m; i++) {
int t1,t2;
t1 = read_In();
t2 = read_In();
printOut(b[t1][t2]);
}
return 0;
}