BFS求调QAQ
查看原帖
BFS求调QAQ
759274
Stevehim楼主2023/9/7 16:07
#include <bits/stdc++.h>
#define maxn 2010
using namespace std;
namespace IO {
	char *p1, *p2, buf[15000];
//#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,15000,stdin),p1==p2)?EOF:*p1++)
#define nc() getchar()
	inline int read() {
		int x = 0, f = 1;
		char ch = nc();
		while (ch < 48 || ch > 57) {
			if (ch == '-')
				f = -1;
			ch = nc();
		}
		while (ch >= 48 && ch <= 57)
			x = (x << 1) + (x << 3) + (ch ^ 48),
			ch = nc();
		return x * f;
	}
}
using IO::read;
char ch[maxn][maxn];
int r, c;
struct node {
	int x, y, len, step;
};
queue<node> q;
int _nxt[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
struct Tmp {
	int x, y;
} tmp[4][maxn][maxn];
int Len;
int vis[maxn][maxn];
bool book[maxn][maxn];
int mi = INT_MAX;
char s[maxn * 5]; //匹配串
string str;
void init() {
	for (int i = 1; i <= r; i++) { // 枚举
		for (int j = 1; j <= c; j++) {
			for (int k = 0; k < 4; k ++) { //统计的是方向
				int tx = i, ty = j;
				while (ch[tx][ty] == ch[tx + _nxt[k][0]][ty + _nxt[k][1]]) {
					tx += _nxt[k][0], ty += _nxt[k][1]; //如果相等,加上
				}
				tmp[k][i][j] = (Tmp) {
					tx, ty
				};  //记录方向
			}
		}
	}
}

void bfs() {
	int tx, ty;
	while (!q.empty()) {
		int x = q.front().x, y = q.front().y, len = q.front().len, step = q.front().step;
		q.pop();
		cout << len << endl;
		if (len == Len + 1) {
			cout << "OK" << endl;
			mi = min(mi, step);
			return;
		}
		if (ch[x][y] == s[len]) {
			q.push((node) {
				x, y, len + 1, step + 1
			});
			vis[x][y] = max(vis[x][y], len + 1); //坐标不变,因为此处按下
		}
		for (int i = 0; i < 4; i++) {
			tx = tmp[i][x][y].x + _nxt[i][0], ty = tmp[i][x][y].y + _nxt[i][1];
//			cout << tx << ' ' << ty << ' ' << len << endl;
			if (tx < 1 || ty < 1 || tx > r || ty > c) continue;
			if (len > vis[tx][ty]) {
				q.push((node) {
					tx, ty, len, step + 1
				});
				vis[tx][ty] = len; //直接更新
			}
		}
	}
}


int main() {
	r = read(), c = read();
	for (int i = 1; i <= r; i++) {
		cin >> str;
		for (int j = 1; j <= c; j++) {
			ch[i][j] = str[j - 1];
			book[i][j] = true;
		}
	}
	scanf("%s", s); //读入匹配串
	Len = strlen(s); // 设定长度
	init();  //尝试初始化
//	cout << tmp[0][2][1].y << endl;
	if (ch[1][1] == s[0]) q.push((node) {
		1, 1, 1, 1
	}), vis[1][1] = 1; //起点开始
	for (int i = 0; i < 4; i++) {
		int tx = tmp[i][1][1].x + _nxt[i][0]; //能去的地方
		int ty = tmp[i][1][1].y + _nxt[i][1];
		if(tx < 1 || ty < 1 || tx > r || ty > c) continue;
//		cout << tx << ' ' << ty << endl;
		q.push((node) {tx, ty, 0, 1}); //只要坐标合规就能进队,因为刚开始的时候也不分来时和去时
	}
	bfs();
	cout << mi;
	return 0;
}
2023/9/7 16:07
加载中...