简易迷宫

#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
//#define _CRT_SECURE_NO_WARNINGS
#define row 5
#define col 5
struct pos
{
 int _row; //行
 int _col; //列
};
void map(int *a)
{
 int j = 0;
 assert(a);
 FILE *fout = (FILE*)fopen("D:\\学习笔记\\迷宫.txt", "r");
 assert(fout);
 for (int i = 0; i < row; i++)
 {
  for (j = 0; j < col;)
  {
   char ch = fgetc(fout);
   if (ch >= '0'&&ch <= '9')
   {
    a[i*col + j] = ch - '0';
    j++;
   }
  }
 
 }
}
int seachrode(int *a,pos entry)//给过来图和入口
{
 assert(a);
 pos CT = entry;
 pos cur = CT;
 a[CT._row*row + CT._col] = 2;//从这进来的,说明已经走过了,标记为2
 
 if ((CT._row != row - 1) && (CT._col != col - 1))//表示还没出去,进行上下左右的遍历
 {
  //往左走
  if ((CT._col - 1) >= 0 && (a[CT._row*row + CT._col - 1] == 0))//注意这里的行和列是可以等于0的
  {
   cur = CT;
   cur._col--;
   if (seachrode(a, cur))
    return 1;
   else
    a[cur._row*row + cur._col] = 3;//说明是死路,要退回来,用3来标记
  }
  //往右走
  if ((CT._col + 1) < row && (a[CT._row*row + CT._col + 1]) == 0)
  {
   cur = CT;
   cur._col = cur._col + 1;
   if (seachrode(a, cur))
    return 1;
   else
    a[cur._row*row + cur._col] = 3;
  }
  //往上走
  if ((CT._row + 1<=0) && (a[(CT._row + 1)*row + CT._col]) == 0)
  {
   cur = CT;
   cur._row = cur._row + 1;
   if (seachrode(a, cur))
    return 1;
   else
    a[cur._row*row + cur._col] = 3;
  }
  //往后走
  if ((CT._row - 1) >= 0 && a[(CT._row - 1)*row + CT._col] == 0)
  {
   cur = CT;
   cur._row = cur._row - 1;
   if (seachrode(a, cur))
    return 1;
   else
    a[cur._row *row + cur._col] = 3;
  }
  return 0;
 }
 else
  return 1;
}
void print(int *a)
{
 assert(a);
 for (int i = 0; i <col; i++)
 {
  for (int j = 0; j < row; j++)
  {
   cout << a[i*row + j];
  }
  cout << endl;
 }
}
void Funtest()
{
 int *a = new int[row*col];
 int ret = 0;
 pos entry;
 entry._row = 3;
 entry._col = 1;
 map(a);
 print(a);
 ret = seachrode(a, entry);
 if (ret == 0)
  cout << "未找到" << endl;
 if (ret == 1)
  cout << "找到了" << endl;
 print(a);
}
int main()
{
 Funtest();
 
 system("pause");
 return 0;
}


结果:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值