七十分不会优化,求大佬帮助
#include <iostream>
#include <queue>
#include <cstring>
#define x first
#define y second
using namespace std;
const int N = 1001;
const int M = 100001;
typedef pair<int, int> PII;
char mp[N][N];
bool st[N][N];
PII ask[M];
queue<PII> q;
int cnt, n, m;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
bool Try(char ch1, char ch2) {
if(ch1 == '0' && ch2 == '1') return true;
if(ch1 == '1' && ch2 == '0') return true;
return false;
}
void init(void) {
cnt = 1;
memset(st, false, sizeof(st));
while(!q.empty()) q.pop();
}
void bfs(int sx, int sy) {
q.push({sx, sy});
st[sx][sy] = true;
while(!q.empty()) {
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int a = t.x + dx[i];
int b = t.y + dy[i];
if(a > n || a < 1 || b > n || b < 1) continue;
if(st[a][b]) continue;
if(Try(mp[t.x][t.y], mp[a][b])) {
st[a][b] = true;
q.push({a, b});
cnt++;
}
}
}
}
int main(void) {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
cin >> mp[i][j];
}
}
for(int i = 1; i <= m; i++) {
init();
int t1, t2;
cin >> t1 >> t2;
bfs(t1, t2);
cout << cnt << endl;
}
return 0;
}