图的遍历
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int Graph[][9] = {
{0, 1, 1, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0},
};
int vis[9] = {0};
void DFS(int g[][9], int v) { // 深度优先遍历算法
cout << v + 1 << " ";
vis[v] = 1;
for (int i = 0; i < 9; i++) {
if (Graph[v][i] && !vis[i]) {
DFS(Graph, i);
}
}
}
queue<int> myQue;
void BFS(int g[][9], int v) { // 广度优先遍历算法
cout << v + 1 << " ";
myQue.push(v);
vis[v] = 1;
while (!myQue.empty()) {
int front = myQue.front();
for (int i = 0; i< 9; i++) {
if (Graph[front][i] && !vis[i]) {
vis[i] = 1;
cout << i + 1 << " ";
myQue.push(i);
}
}
myQue.pop();
}
}
int main()
{
cout << "Depth-First Search: ";
DFS(Graph, 0);
memset(vis, 0, sizeof(vis));
cout << "\n\nBreadth-First Search: ";
BFS(Graph, 0);
memset(vis, 0, sizeof(vis));
cout << "\n\n";
return 0;
}
迷宫问题
题目描述
小明得到一张迷宫地图,他想从(1,1)出发,找一条最短的到(8,8)的路径。
输入
现输入整数N,表示数据包含N行N列个数。然后输入四个整数,分别表示起点和终点的行列值。
然后是N行N列个数,0表示可以通过,1表示不能通过
输出
最短要走几步
样例输入
8
1 1 8 8
0 0 0 0 0 0 0 0
0 1 1 1 1 0 1 0
0 0 0 0 1 0 1 0
0 1 0 0 0 0 1 0
0 1 0 1 1 0 1 0
0 1 0 0 0 0 1 1
0 1 0 0 1 0 0 0
0 1 1 1 1 1 1 0
样例输出
14
#include <iostream>
#include <queue>
using namespace std;
typedef struct Node {
int x;
int y;
int v;
};
Node path[59][59];
void bfs(int x, int y) {
queue<Node> myQue;
path[x][y].v = 1;
myQue.push(path[x][y]);
while (!myQue.empty()) {
Node front = myQue.front();
if (!path[front.x+1][front.y].v) {
path[front.x+1][front.y].v = front.v + 1;
myQue.push(path[front.x+1][front.y]);
}
if (!path[front.x][front.y+1].v) {
path[front.x][front.y+1].v = front.v + 1;
myQue.push(path[front.x][front.y+1]);
}
myQue.pop();
}
}
void Clear(int n) {
for (int i = 0; i <= n + 5; i++)
for (int j = 0; j <= n + 5; j++) {
path[i][j].v = 1;
path[i][j].x = i;
path[i][j].y = j;
}
}
int main() {
int n, x1, y1, x2, y2;
while (cin >> n) {
Clear(n); // 重置数组
cin >> x1 >> y1 >> x2 >> y2;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> path[i][j].v;
}
bfs(x1, y1);
for (int ii = 1; ii <= n; ii++){
for (int jj = 1; jj <= n; jj++) {
cout << path[ii][jj].v << " ";
}
cout << endl;
}
cout << path[x2][y2].v - 1 << endl; // 起点不算, 需减掉
}
return 0;
}