重回OI的第一篇博客

太久没学OI了,
代码都不会写了,
先写一篇BFS练练手,
是我太菜了qwq

#include<cstdio>
#include<queue>
#include<iostream>
#include<cstring>
using namespace std;
struct node{
	int x,y,step;
};
queue<node>q;
char a[21][21];
int n,m,b[21][21],tx,ty;
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
node start,tmp;
void bfs(int xx,int yy){
	while(q.size()) q.pop();
	memset(b,0,sizeof(b));
	b[xx][yy]=1;
	start.x=xx; start.y=yy; start.step=0;
	q.push(start);
	while(q.size()){
		start=q.front();
		for(int i=0;i<4;i++){
			tx=start.x+dx[i]; ty=start.y+dy[i];
			if(a[tx][ty]=='*'){
				printf("%d\n",start.step+1);
				return;
			}
			if(tx>0&&tx<=n&&ty>0&&ty<=m&&!b[tx][ty]&&a[tx][ty]=='.'){
				b[tx][ty]=1;
				tmp.x=tx; tmp.y=ty; tmp.step=start.step+1;
				q.push(tmp);
			}
		}
		q.pop();
	}
	printf("-1\n");
}
int main(){
	int xx,yy;
	while(1){
		scanf("%d%d",&n,&m);
		if(n==0&&m==0) return 0;
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++){
				cin>>a[i][j];
				if(a[i][j]=='@') xx=i,yy=j;
			}
		bfs(xx,yy);
	}
}

一道非常水的BFS(尽管我写了好久
好不容易又开始学OI了,
慢慢重新学叭qwq

posted @ 2020-07-19 14:08  sshadows  阅读(160)  评论(2编辑  收藏  举报