hdu 1242BFS 不過+DFS過

來源:互聯網
上載者:User

/*拿道題就BFS,結果與題意不符,後改DFS

#include<iostream>
#include<queue>
using namespace std;
struct st{
 int x;
 int y;
 int step;
};
char a[201][201];
int b[201][201];
int c[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int sx,sy,ex,ey;
int m,n;
bool k;
void bfs(){
// memset(b,0,sizeof(b));
 queue <st> Q;
 st q,s;
 q.x=sx;q.y=sy;q.step=0;
 b[sx][sy]=1;
 Q.push(q);
 while(!Q.empty()){
  s=Q.front();
  if(s.x==ex&&s.y==ey){
   k=1;
   cout<<s.step<<endl;
   return ;
  }
  Q.pop();
  int i;
  for(i=0;i<4;i++){
   q.x=s.x+c[i][0];q.y=s.y+c[i][1];
   if(q.x<0||q.y<0||q.x>=m||q.y>=n) continue;
   if(b[q.x][q.y]==1) continue;
   if(a[q.x][q.y]=='.') q.step=s.step+1;
   else if(a[q.x][q.y]=='x') q.step=s.step+2;
   Q.push(q);b[q.x][q.y]=1;
  }
 }
 return ;
}
int main(){
  freopen("1.txt","r",stdin);
 freopen("2.txt","w",stdout);
 while(cin>>m>>n){
  int i,j;k=0;
  for(i=0;i<m;i++){
   for(j=0;j<n;j++){
    cin>>a[i][j];
    if(a[i][j]=='.'||a[i][j]=='x') b[i][j]=0;
    else if(a[i][j]=='#') b[i][j]=1; 
    else if(a[i][j]=='r') {sx=i;sy=j;}
    else if(a[i][j]=='a') {ex=i;ey=j;}
   }
  }
  bfs();
  if(k==0) cout<<"Poor ANGEL has to stay in the prison all his life. /n";
 }
 return 0;
}*/
***************************************************

#include<iostream>
using namespace std;
char a[201][201];
int c[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int sx,sy,ex,ey;
bool l;int m,n;
int minn=100000;
void dfs(int x,int y,int t){
 int q,p;
// if(x<0||y<0||x>=m||y>=n) return ;
 if(x==ex&&y==ey){
  l=1;
  if(minn>t) minn=t;
  return;
 }
 int i;
 for(i=0;i<4;i++){
  q=x+c[i][0];p=y+c[i][1];
  if(a[q][p]!='#'&& p >= 0 && p < n && q >= 0 && q < m){
  if(a[q][p]=='x'){
   a[q][p]='#';
   dfs(q,p,t+2);
   a[q][p]='x';
  }
  else {//if(a[q][p]=='.'||a[q][p]=='r')注意邊界!!!2啊!
   a[q][p]='#';
   dfs(q,p,t+1);
   a[q][p]='.';
  }
     }
 }
 return ;
}
int main(){
  freopen("1.txt","r",stdin);
 freopen("2.txt","w",stdout);
  while(cin>>m>>n){
   int i,j;l=0;minn=1000000;
   for(i=0;i<m;i++){
    for(j=0;j<n;j++){
     cin>>a[i][j];
     if(a[i][j]=='a')
     { sx=i;sy=j;}
     if(a[i][j]=='r')
     { ex=i;ey=j;}
    }
   }
   a[sx][sy]='#';
   dfs(sx,sy,0);
   if(l) cout<<minn<<endl;
   else cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
  }
  return 0;
}
  
 
 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.