数据结构迷宫问题C/C++链栈实现

更新:使用回溯法求解迷宫问题(获取最优路径)

原文章使用方法过于愚蠢,请忽略

说明 N 代表迷宫,A代表方位暂存器,V代表对应的N点是否被访问,AS代表方位存储器,Step代表下一步的操作。

#include<iostream>
using namespace std;

int N[10001][10001];
int A[10001][2];
int V[10001][10001];
int AS[10001][2];
int Step[4][2] = {
  {0,1},{0,-1},{1,0},{-1,0}};

int n;
int MinStep = 100000;

void Search(int s){
	for(int i=0;i<4;i++){
		int x = A[s-1][0]+Step[i][0];
		int y = A[s-1][1]+Step[i][1];
		if(x>=1 && x<=n && y>=1 && y<=n && V[x][y] != 1 && N[x][y] != 1 && s<MinStep){
			V[x][y] = 1;
			A[s][0] = x;
			A[s][1] = y;
			if(A[s][0] == n && A[s][1] == n){
				if(s<MinStep){
					for(int j=1;j<=s;j++){
						AS[j][0] = A[j][0];
						AS[j][1] = A[j][1];
					}
					MinStep = s;
				}
			}else{
				Search(s+1);
			}
			V[x][y] = 0;
		}
		
	}
}
int main(){
	A[1][0] = A[1][1] = 1;
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>N[i][j];
		}
	}
	Search(2);
	cout<<MinStep<<endl;
	for(int j=1;j<=MinStep;j++){
		cout<<AS[j][0]<<" "<&
  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,迷宫问题可以使用深度优先搜索(DFS)算法进行解决,以下是一个使用C语言实现迷宫问题解决方案: ```c #include <stdio.h> #include <stdlib.h> #define ROW 5 #define COL 5 // 定义迷宫地图:0表示可以通行,1表示障碍物 int maze[ROW][COL] = { {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 dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // 定义位置结构体 typedef struct { int row; int col; } Position; // 定义结构体 typedef struct { Position pos[ROW * COL]; int top; } Stack; // 初始化 void initStack(Stack *s) { s->top = -1; } // 判断是否为空 int isEmpty(Stack *s) { return s->top == -1; } // 入 void push(Stack *s, Position p) { s->top++; s->pos[s->top] = p; } // 出 void pop(Stack *s) { s->top--; } // 获取顶元素 Position top(Stack *s) { return s->pos[s->top]; } // 判断位置是否合法 int isValidPos(int row, int col) { if (row < 0 || row >= ROW || col < 0 || col >= COL) { return 0; } if (maze[row][col] == 1) { return 0; } return 1; } // 深度优先搜索算法 void DFS() { Stack s; initStack(&s); Position startPos = {0, 0}; push(&s, startPos); maze[startPos.row][startPos.col] = 1; // 标记为已访问 while (!isEmpty(&s)) { Position curPos = top(&s); if (curPos.row == ROW - 1 && curPos.col == COL - 1) { printf("已找到出口!\n"); return; } int i; for (i = 0; i < 4; i++) { Position newPos = {curPos.row + dir[i][0], curPos.col + dir[i][1]}; if (isValidPos(newPos.row, newPos.col)) { push(&s, newPos); maze[newPos.row][newPos.col] = 1; // 标记为已访问 break; } } if (i == 4) { pop(&s); } } printf("未找到出口!\n"); } int main() { DFS(); return 0; } ``` 以上代码中,使用了一个结构体来模拟深度优先搜索算法的递归过程,每次将符合条件的邻居位置入,直到找到出口或者为空。其中isValidPos函数用于判断位置是否合法,dir数组用于定义四个方向,maze数组用于存储迷宫地图,0表示可以通行,1表示障碍物。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值