基于栈实现广度优先搜索c语言
时间: 2023-10-11 07:08:44 浏览: 47
广度优先搜索(BFS)是一种基于队列的搜索算法,而不是基于栈。但是,如果你想要用栈实现BFS,可以使用迭代深化搜索(IDS)算法,它是一种基于栈的搜索算法。
以下是在C语言中使用栈实现IDS的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_DEPTH 100
int visited[100] = {0};
// 栈结构体
struct Stack {
int data[MAX_DEPTH];
int top;
};
// 创建栈
struct Stack* createStack() {
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->top = -1;
return stack;
}
// 判断栈是否为空
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// 入栈
void push(struct Stack* stack, int item) {
stack->data[++stack->top] = item;
}
// 出栈
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top--];
}
// 栈顶元素
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top];
}
// IDS搜索算法
int IDS(int graph[][100], int start, int end) {
int depth = 0;
int i, j;
struct Stack* stack = createStack();
while (depth < MAX_DEPTH) {
int visitedNodes[100] = {0};
push(stack, start);
visited[start] = 1;
visitedNodes[start] = 1;
while (!isEmpty(stack)) {
int node = pop(stack);
if (node == end) {
return 1;
}
for (i = 0; i < 100; i++) {
if (graph[node][i] == 1 && visited[i] == 0 && visitedNodes[i] == 0) {
push(stack, i);
visited[i] = 1;
visitedNodes[i] = 1;
}
}
}
depth++;
}
return 0;
}
int main() {
int graph[100][100] = {0};
int start, end, i, j, n;
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the graph in adjacency matrix form:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the start node: ");
scanf("%d", &start);
printf("Enter the end node: ");
scanf("%d", &end);
if (IDS(graph, start, end)) {
printf("Path exists between %d and %d\n", start, end);
} else {
printf("No path exists between %d and %d\n", start, end);
}
return 0;
}
```
注意:这里的代码只是用栈实现了IDS搜索算法,并不是BFS算法。如果你想要使用BFS算法,请使用队列来实现。