64,653
社区成员
发帖
与我相关
我的任务
分享
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#define MAXL 4
using namespace std;
struct Node
{
int x,y;
Node(int x=0,int y=0) : x(x),y(y) {}; //构造函数或者写成Node(int x=0,int y=0) { this->x = x;this->y = y; }
};
bool Bfs(Node Vs,Node Vd);
int mg[5][5]={0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0};
int main()
{
Node Vs(0,0),Vd(4,4);
if(Bfs(Vs,Vd))
cout << Vs.x;
cout <<"yes";
}
int isValid(struct Node& Vw)
{
if(!mg[Vw.x][Vw.y])
return 1;
else return 0;
}
/**
* 广度优先搜索
* @param Vs 起点
* @param Vd 终点
*/
int Bfs(Node& Vs, Node& Vd){
queue<Node> Q;
Node Vn, Vw;
int i;
//用于标记颜色当visit[i][j]==true时,说明节点访问过,也就是黑色
bool visit[MAXL][MAXL];
//四个方向
int dir[][2] = {
{0, 1}, {1, 0},
{0, -1}, {-1, 0}
};
//初始状态将起点放进队列Q
Q.push(Vs);
visit[Vs.x][Vs.y] = true;//设置节点已经访问过了!
while (!Q.empty()){//队列不为空,继续搜索!
//取出队列的头Vn
Vn = Q.front();
Q.pop();
for(i = 0; i < 4; ++i){
Vw = Node(Vn.x+dir[i][0], Vn.y+dir[i][1]);//计算相邻节点
if (Vw.x == Vd.x && Vw.y == Vd.y){//找到终点了!
//把路径记录,这里没给出解法
return 1;//返回
}
if (isValid(Vw) && !visit[Vw.x][Vw.y]){
//Vw是一个合法的节点并且为白色节点
Q.push(Vw);//加入队列Q
visit[Vw.x][Vw.y] = true;//设置节点颜色
}
}
}
return 0;//无解
}
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#define MAXL 4
using namespace std;
struct Node
{
int x,y;
Node(int x=0,int y=0) : x(x),y(y) {}; //构造函数或者写成Node(int x=0,int y=0) { this->x = x;this->y = y; }
};
// bool Bfs(Node& Vs,Node& Vd);
int mg[5][5]={0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,0};
//int main()
//{
// Node Vs(0,0),Vd(4,4);
// if(Bfs(Vs,Vd))
// cout << Vs.x;
// cout <<"yes";
//}
int isValid(struct Node& Vw)
{
if(!mg[Vw.x][Vw.y])
return 1;
else return 0;
}
/**
* 广度优先搜索
* @param Vs 起点
* @param Vd 终点
*/
int Bfs(Node& Vs, Node& Vd){
queue<Node> Q;
Node Vn, Vw;
int i;
//用于标记颜色当visit[i][j]==true时,说明节点访问过,也就是黑色
bool visit[MAXL][MAXL];
//四个方向
int dir[][2] = {
{0, 1}, {1, 0},
{0, -1}, {-1, 0}
};
//初始状态将起点放进队列Q
Q.push(Vs);
visit[Vs.x][Vs.y] = true;//设置节点已经访问过了!
while (!Q.empty()){//队列不为空,继续搜索!
//取出队列的头Vn
Vn = Q.front();
Q.pop();
for(i = 0; i < 4; ++i){
Vw = Node(Vn.x+dir[i][0], Vn.y+dir[i][1]);//计算相邻节点
if (Vw.x == Vd.x && Vw.y == Vd.y){//找到终点了!
//把路径记录,这里没给出解法
return 1;//返回
}
if (isValid(Vw) && !visit[Vw.x][Vw.y]){
//Vw是一个合法的节点并且为白色节点
Q.push(Vw);//加入队列Q
visit[Vw.x][Vw.y] = true;//设置节点颜色
}
}
}
return 0;//无解
}
int main(int argc, char** argv) {
Node Vs(0,0),Vd(4,4);
if(Bfs(Vs,Vd))
cout << Vs.x;
cout <<"yes";
return 0;
}