![]() |
#2
komorebi01102020-04-19 21:11
#include<stdio.h>
#include<iostream> using namespace std; class migong { public: migong(); void initial(); int jisuan(); void seten(); void solved(int x,int y,int n); private: int Migong[12][12]; int step; int Ex; int Ey; }; migong::migong() { step=1000000; } void migong::initial() { step=1000000; } void migong::seten() { for(int i = 0; i<12; i++) { for(int j = 0; j < 12; j++) { char temp; cin>>temp; if(temp=='W') Migong[i][j]=1; else if(temp=='E') { Ex=i; Ey=j; Migong[i][j]=0; } else if(temp=='O') Migong[i][j]=0; } } } void migong::solved(int x,int y,int n) { if(Migong[x][y]!=0) return; if(x==Ex&&y==Ey) { step=min(step,n); return; } if(x > 0) solved(x-1,y,n+1); if(y > 0) solved(x,y-1,n+1); if(x < 11) solved(x+1,y,n+1); if(y < 11) solved(x,y+1,n+1); Migong[x][y]=0; return; } int migong::jisuan() { return step; } int main() { migong A; A.seten(); for(int i=0;i<3;i++) { A.initial(); int x,y; char c; cin>>c>>x>>c>>y>>c; A.solved(x,y,0); if(A.jisuan()==1000000) cout << "-1"; else cout << A.jisuan()+1 <<' '; } } //最近刚学了八皇后问题,知道什么叫回溯...看不出来问题在哪里QAQ |
A maze is to be represented by a 12*12 array composed of three values: Open, Wall, or Exit. There is one exit from the maze. Write a program to determine whether it is possible to exit the maze from the starting point (any open square can be a starting point). You may move vertically and horizontally to any adjacent open square(左右上下四个方向). You may not move to a square containing a wall. The input consists of a series of 12 lines of 12 characters each, representing the contents of each square in the maze. The characters are O, W, or E.
【输入】 12×12的迷宫方阵,每个格子的可能取值有:O, W, or E,输入数据能够确保迷宫只有一个出口。
任意3个起点的坐标,格式如下(x,y)。其中x为纵坐标,y为横坐标,起始坐标从左上角的格子开始,坐标起始值为0.
【输出】
起点到出口的最短路径长度(经过多少个方格),若起点无法到达出口则输出-1。起始节点和结束节点都算入路径长度的计算。
例如:
【输入】
O W O W O W O O W O W O
O W O W W W W O W O O E
O W W W O O O O O O O O
W W W O O O O W W W O W
O O O O W W W O O O O O
O O W O W O W O W O W W
O W W O O O W W O O O W
O O W O O W W W O O O O
O O O W O O O O W W W W
W W W O O O O W W W O O
O W W W W O O O O O W W
W W W O O O O O W W W W
(0,0) (5,7) (7,8)
【输出】
-1 9 10
【解释】
输出表示第一个点(0,0)无法到达出口;
第二个点(5,7)到达出口的最短路径是9;
第三个点(7,8)到达出口的最短路径是10;