The shortest path problem --- breadth-first search solution

Enter a value n, represents an area of ​​nxn, where the value 1 represents a strong signal, weak signal indicates 0, for example:

3

1 0 1

1 1 1

1 1 1

Find all strong signal paths (not including 0) in the shortest path, and the output value of the shortest path, the shortest path if there is no (not to the bottom right), the output of -1.

Ideas: the entire nxn array to build a two-dimensional map, using the breadth-first search algorithm to search until the small angle hit the right elements.

code show as below:

#include <iostream>
#include <vector>
#include <queue>//用队列实现广度优先搜索
using namespace std;

struct Node//图的节点
{
	bool tovisit;//该节点是否将要被访问
	int val, x, y;//存储该节点的值以及坐标
	Node *upper,*left,*down,*right;//存储该节点周围的情况
	Node():tovisit(false),val(-1),upper(NULL), left(NULL), down(NULL), right(NULL){}
};

int main()
{
	int n;
	cin>>n;
	vector<Node> a(n);
	vector<vector<Node>> A(n, a);//注意初始化第一个参数为元素个数,第二个参数为数据类型
	for(int i=0; i<n; i++){
		for(int j=0; j<n; j++){
			cin>>A[i][j].val;
			if(i-1>=0)
				A[i][j].upper=&A[i-1][j];
			if(j-1>=0)
				A[i][j].left=&A[i][j-1];
			if(i+1<=n-1)
				A[i][j].down=&A[i+1][j];
			if(j+1<=n-1)
				A[i][j].right=&A[i][j+1];
			A[i][j].x=i;
			A[i][j].y=j;
		}
	}//给所有节点赋值,并且连接其上下左右的节点
	int dis=-1;
	queue<Node*> S;//S中存储节点的位置(Node*)
	if(A[0][0].val==0)
		return -1;
	S.push(&A[0][0]);
	A[0][0].tovisit=true;
	while(!S.empty()){//队列非空
		int length=S.size();
		for(int i=0; i<length; i++){//广度优先搜索
			Node* cur=S.front();
			S.pop();
			if(cur->x==n-1&&cur->y==n-1){
				cout<<dis+1;
				system("pause");
				return 0;
			}
			/*将下一层节点加入到队列中*/
			if(cur->upper&&!cur->upper->tovisit&&cur->upper->val==1){
				S.push(cur->upper);
				cur->upper->tovisit=true;
			}
			if(cur->left&&!cur->left->tovisit&&cur->left->val==1){
				S.push(cur->left);
				cur->left->tovisit=true;
			}
			if(cur->down&&!cur->down->tovisit&&cur->down->val==1){
				S.push(cur->down);
				cur->down->tovisit=true;
			}
			if(cur->right&&!cur->right->tovisit&&cur->right->val==1){
				S.push(cur->right);
				cur->right->tovisit=true;
			}
		}//遍历完每一层后
		dis++;//将距离+1
	}
	cout<<-1;
	system("pause");
	return 0;
}

 

Published 18 original articles · won praise 0 · Views 791

Guess you like

Origin blog.csdn.net/afiguresomething/article/details/102596149