最近做了几道bfs题,总的来说有部分代码是几乎不用去改动的,比如用队列实现bfs的流程。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct Node{
int x,y,cnt;
};
int mp[1001][1001];
int vis[1001][1001];
bool judge(){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(a[i][j] < 2)continue;
}
}
}
int n,m,sc,sr,newColor;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int bfs(int x, int y, int newColor){
Node p;
p.x = x;
p.y = y;
p.cnt = 0;
queue<Node>q;
q.push(p);
while(!q.empty()){
Node k = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int tx = k.x + dir[i][0];
int ty = k.y + dir[i][1];
Node k1;
// k1.x = tx;更新Node
// k1.y = ty;更新Node
// k1.cnt = k.cnt+1;更新Node
if(条件不符合直接跳过)continue;
if(符合条件的进行一系列操作){
// cout<<tx<<","<<ty<<endl;
mp[tx][ty] = 2;
// vis[tx][ty] = 1;
q.push(k1);更新后的Node放入队列中
}
}
}
}
int main(){
ios::sync_with_stdio(false);
while(cin>>n>>m){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin>>mp[i][j];
}
}
cin>>sr>>sc;
bfs(sr,sc);
return 0;
}
搜索题啊搜索题我真的很服很服,就像天生是和我作对一样,真的让我学的很费力!总是因为一些细节导致整个代码失效。