BFS(广度优先搜索)笔记

计数n×m 型01矩阵中1块数:

#include
#include
using namespace std;
const int maxn = 100;
struct node{
	int x,y;
}Node;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};//记录(x,y)是否已入队列
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
bool judge(int x,int y){//判断坐标(x,y)是否需要访问
	if(x>=n||x<0||y>=m||y<0) return false;
	if(matrix[x][y]==0||inq[x][y] == true) return false;
	return true;
}
void BFS(int x,int y){
	queue Q;
	Node.x=x,Node.y=y;
	Q.push(Node);
	inq[x][y] = true;
	while(!Q.empty()){
		node top =Q.front();
		Q.pop();
		for(int i = 0;i< 4;i++){
			int newX=top.x+X[i];
			int newY=top.y+Y[i];
			if(judge(newX,newY)){
				Node.x=newX,Node.y=newY;
				Q.push(Node);
				inq[newX][newY]=true;
			}
		}
	}
}
int main(){
	scanf("%d%d",&n,&m);
	for(int x=0;x

计算在n×m型矩阵中从起点到终点的最少步数:

#include
#include
#include
using namespace std;
const int maxn=100;
struct node{
	int x,y;
	int step;
}S,T,Node;
int n,m;//n为行,m为列
char maze[maxn][maxn];
bool inq[maxn][maxn];
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
bool test(int x,int y){
	if(x>=n||x<0||y>=m||y<0) return false;//超过边界 
	if(maze[x][y]=='*') return false;//遇到墙壁 
	if(inq[x][y]== true) return false;//已过队列 
	return true;//有效位置 
} 
int BFS(){
	queue q;
	q.push(S);
	while(!q.empty()){
		node top=q.front();
		q.pop();
		if(top.x==T.x&&top.y==T.y){
			return top.step;
		}
		for(int i = 0;i<4;i++){
			int newX=top.x+X[i];
			int newY=top.y+Y[i];
			if(test(newX,newY)){
				Node.x=newX,Node.y=newY;
				Node.step = top.step+1;
				q.push(Node);
				inq[newX][newY];
			}
		} 
	}
	return -1;
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i

 

你可能感兴趣的:(算法笔记,搜索)