-
题目描述:
-
sun所在学校每年都要举行电脑节,今年电脑节有一个新的趣味比赛项目叫做闯迷宫。
sun的室友在帮电脑节设计迷宫,所以室友就请sun帮忙计算下走出迷宫的最少步数。
知道了最少步数就可以辅助控制比赛难度以及去掉一些没有路径到达终点的map。
比赛规则是:从原点(0,0)开始走到终点(n-1,n-1),只能上下左右4个方向走,只能在给定的矩阵里走。
-
输入:
-
输入有多组数据。
每组数据输入n(0<n<=100),然后输入n*n的01矩阵,0代表该格子没有障碍,为1表示有障碍物。
注意:如果输入中的原点和终点为1则这个迷宫是不可达的。
-
输出:
-
对每组输入输出该迷宫的最短步数,若不能到达则输出-1。
-
样例输入:
-
2 0 1 0 0 5 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 0 0
-
样例输出:
-
2
8
-
-
///
-
广度优先搜索法,采用队列实现,自己写了个简易版的队列,发现也并没比STL的队列来得快。。。。
-
-
//#include<queue> #include<iostream> #include<stdio.h> #include<stdlib.h> int n; bool v[101][101]; using namespace std; struct du{ int data; du*next; }; class queue { du *head,*tail; int len; public: queue() { len=0; head=NULL; tail=NULL; } bool pop() { du*temp=head; head=head->next; len--; free(temp); return true; } int front() { return head->data; } bool push(int n) { du *temp=new(du); temp->data=n; temp->next=NULL; if(len==0) { head=temp; tail=temp; } else { tail->next=temp; tail=temp; } len++; return true; } bool empty() { if(len==0) return true; else return false; } }; int main() { int j,k,i; int v1,v2,st; while(cin>>n&&n>0) { for(j=0;j<n;j++) for(k=0;k<n;k++) cin>>v[j][k]; queue a; int mi=-1; if(v[0][0]&&v[n-1][n-1]) cout<<-1; else { a.push(0); a.push(0); a.push(0); while(!a.empty()) { v1=a.front(); a.pop(); v2=a.front(); a.pop(); st=a.front(); a.pop(); if(v1==n-1&&v2==n-1) { mi=st; break; } if(!v[v1][v2]) { if(v1+1<n&&!v[v1+1][v2]) { a.push(v1+1); a.push(v2); a.push(st+1); } if(v2+1<n&&!v[v1][v2+1]) { a.push(v1); a.push(v2+1); a.push(st+1); } if(v1-1>=0&&!v[v1-1][v2]) { a.push(v1-1); a.push(v2); a.push(st+1); } if(v2-1>=0&&!v[v1][v2-1]) { a.push(v1); a.push(v2-1); a.push(st+1); } } v[v1][v2]=true; } cout<<mi<<endl; } } return 0; } /************************************************************** Problem: 1335 User: 午夜小白龙 Language: C++ Result: Accepted Time:230 ms Memory:1528 kb ****************************************************************/