这题用了广搜,调试bug调了好久,因为这个解法也是参考网上的方法,到最后改到几乎一样还是不通过,最终发现用了vector后没有及时clear!这就很难找出来bug,每次都是前几个计算结果的重复,困惑解开的时候还是很后悔没有早注意这个地方的。
话说调bug也是个需要灵光一现的事情 —By我
#include<iostream>
#include<queue>
using namespace std;
//P1141 Maze BFS Practice
// By Felix Chang
class node{
public:
int x;
int y;
};
int n,m;
int maze[1000][1000],step[1000][1000]={0};
int visited[1000][1000] = {0};
int dir[4][2] = {-1,0,0,1,1,0,0,-1};//up down left right
queue<node> q;
vector<node> v;
void search(int x,int y)
{
int cnt=1;
node temp;
temp.x=x;temp.y=y;
q.push(temp);v.push_back(temp);
visited[x][y]=1;
while(!q.empty())
{
int xx = q.front().x,yy=q.front().y;
q.pop();
visited[xx][yy] = 1;
for(int i=0;i<4;++i)
{
if(xx+dir[i][0]<n && xx+dir[i][0]>=0 && yy+dir[i][1]<n && yy+dir[i][1]>=0 && !visited[xx+dir[i][0]][yy+dir[i][1]] && maze[xx+dir[i][0]][yy+dir[i][1]]!=maze[xx][yy])
{
node t;
xx += dir[i][0];yy += dir[i][1];
t.x=xx;t.y=yy;
visited[xx][yy] = 1;
cnt++;
q.push(t);v.push_back(t);
xx -= dir[i][0];
yy -= dir[i][1];
}
}
}
for(int i=0;i<v.size();++i) step[v[i].x][v[i].y] = cnt;
v.clear();
}
int main()
{
cin >> n >> m;
string str;
for(int i=0;i<n;++i)
{
cin >> str;
for(int j=0;j<n;++j) maze[i][j] = str[j]-'0';
}
for(int i=0;i<n;++i) for(int j=0;j<n;++j) if(!visited[i][j]) search(i,j);
for(int i=0;i<m;++i) {int x,y; cin >> x >> y; cout << step[x-1][y-1] << endl;}
//God!the bug x-1 and y-1 is disgusting!!!
//cout << dir[0][0] << dir[0][1] ;
return 0;
}