解答C++作业01

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
#include<cstdlib>
using namespace std;

int find(char ch,int &x,int &y,string openMaze,int& width )
{ string str;
 ifstream fin(openMaze.c_str());
 if(!fin)
  {cout<<"can't open"<<endl;
  return 0;}
 while(getline(fin,str))
 { x++;
  y=str.find(ch,0);
  if(y!=string::npos)
  break;
 }
 width=str.size();
 fin.close();
 x--;
 return 1;
}//find 'e' and return width

int loadMap(string* load,string openMaze,int & height)
{ string str;
 ifstream fin(openMaze.c_str());
 if(!fin)
  {cout<<"can't open"<<endl;
  return 0;}
 while(getline(fin,str))
 {
  load[height]=str;
   height++;
 }
 
 fin.close();
 return 1;
}//load the map into a string pointer and return height
//method:
//1.R  2.D  3.L  4.U
//o------>
//|      |
//|<-----V
bool findWay(int x,int y,string* load)
{
 load[x][y]='O';
 
 if (load[x+1][y]=='x') return true;
 if (load[x-1][y]=='x') return true;
 if (load[x][y+1]=='x') return true;
 if (load[x][y-1]=='x') return true;
 if (load[x][y+1]=='.')
 {
  if(findWay(x,y+1,load)==true)
   return true;
 }
 if (load[x+1][y]=='.')
 {
  if(findWay(x+1,y,load)==true)
  return true;
 }
  if (load[x][y-1]=='.')
 {
  if(findWay(x,y-1,load)==true)
  return true;
 }
 if (load[x-1][y]=='.')
 {
   if(findWay(x-1,y,load)==true)
  return true;
 }
 
  load[x][y]='.';
  return false;
}//use square to sign where it has been ,if can't go through,turn it back to '.'

int main()

 int i,width=0,height=0;
 int x=0,y=0,x1=0,y1=0;
 //int director;
 string openMaze;
 cout<<"which map do you like to play?maze1.txt or maze2.txt?"<<endl;
 cin>>openMaze;
 cout<<endl;
 
 if(find('e',x,y,openMaze,width))
 {cout<<"can find entrance  ";
 cout<<"x: "<<x<<" y: "<<y<<"!"<<endl;}
 else {cout<<"can't find entrance !"<<endl;
  return 1;
 }
 if(find('x',x1,y1,openMaze,width))
 {cout<<"can find exit  ";
 cout<<"x: "<<x1<<" y: "<<y1<<"!"<<endl;}
 else {cout<<"can't find exit !"<<endl;
  return 1;
 }
  
    string* load=new string[width];//create the string pointer to load map

 loadMap(load,openMaze,height);
 cout<<"the map is :"<<height<<" *  "<<width<<" type."<<endl;
 load[x][y]='/004';load[x1][y1]='/004';
 for (i=0;i<=height;i++)
  cout<<load[i]<<endl;

 load[x1][y1]='x';
 if (findWay(x,y,load))
 { 
  cout<<"can find the way!"<<endl;
  for (i=0;i<=height;i++)
   cout<<load[i]<<endl;
  
 }
 else cout<<"can't find,sorry!"<<endl;
 
 delete [] load;
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值