迷宫问题:关键是检测及行走部分的代码

/*
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
ans=4
*/
#include<stdio.h>
#include<queue>
using namespace std;
const int maxn= 100;
int X[4]={0,0,1,-1};//左和下为正方向
int Y[4]={1,-1,0,0};
int mat[maxn][maxn];
bool visit[maxn][maxn]={false};
int n,m;
bool judge(int x,int y){//判断当前坐标是否合法即该点是否可以加入:不能越界;不能为0
	if(x>=n || x<0 || y>=m || y<0)	return false;
	if(mat[x][y]==0 || visit[x][y]==true)	return false;
	return true;
}
struct Node{
	int x, y;
}node;

//在四个不同的方向上进行遍历
void BFS(int x,int y){
	queue<Node>	q;
	node.x=x;
	node.y=y;
	q.push(node);
	visit[x][y]=true;
	while(!q.empty()){
		Node temp=q.front();
		q.pop();
		for(int i=0;i<4;i++){//在四个方向上选择合适的点入队
			int NewX=temp.x+X[i];
			int NewY=temp.y+Y[i];
			if(judge(NewX,NewY)){
				node.x=NewX;node.y=NewY;
				q.push(node);
				visit[NewX][NewY]=true;
			}
		}
	}
}

int main(){
	int m,n;
	scanf("%d%d",&m,&n);
	for(int x=0;x<n;x++)
		for(int y=0;y<m;y++)
			scanf("%d",&mat[x][y]);
	int ans=0;
	//BFS遍历所有没有遍历到的区块
	for(int x=0;x<n;x++)
		for(int y=0;y<m;y++){
			if(!visit[x][y] && mat[x][y]==1){
				ans++;
				BFS(x,y);
			}
		}

	printf("%d",ans);
	return 0;
} 

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/futangxiang4793/article/details/79506891
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞