zoukankan      html  css  js  c++  java
  • K

    又是给一个迷宫找最短路径,不过不同的是要把路径输出

    思路:先写一个正常的BFS,但是多加入一个数组,记录每个点的上一个点,到达最后一个点时再DFS向上搜索路径

    #include<iostream>
    #include<queue>
    #include<string.h>
    
    using namespace std;
    
    typedef long long ll;
    typedef unsigned long long ull;
    
    int maze[5][5];
    int d[5][5];
    int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
    pair<int, int> last[5][5];
    
    void dfs(int x, int y){
      if( x || y )
        dfs(last[x][y].first, last[x][y].second);
      cout << "(" << x << ", " << y << ")" << endl;
    }
    void bfs(int x, int y){
      queue< pair<int, int> > q;
      q.push(pair<int, int>(x, y));
      d[x][y] = 0;
    
    
      while( !q.empty() ){
        pair<int, int> t = q.front(); q.pop();
        if(t.first == 4 && t.second == 4){
          dfs(last[t.first][t.second].first, last[t.first][t.second].second);
          cout << "(" << t.first << ", " << t.second << ")" << endl;
          return;
        }
        for(int i=0; i<4; i++){
          int nx = t.first + dx[i];
          int ny = t.second + dy[i];
          if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && d[nx][ny] == -1 && maze[nx][ny] != 1){
            d[nx][ny] = d[t.first][t.second] + 1;
            last[nx][ny].first = t.first;
            last[nx][ny].second = t.second;
            q.push(pair<int, int>(nx, ny));
          }
        }
      }
    }
    
    int main(){
      ios::sync_with_stdio(false);
      for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
          cin >> maze[i][j];
    
      memset(d, -1, sizeof d);
      for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
          last[i][j].first = last[i][j].second = -1;
    
      bfs(0, 0);
    
      return 0;
    }
  • 相关阅读:
    甘超波:NLP五步脱困法
    甘超波:NLP换框法
    甘超波:NLP先跟后带
    甘超波:NLP瞬间亲和力
    甘超波:NLP回应与建议技巧
    甘超波:NLP复述
    甘超波:NLP新旧ABC觉察法
    甘超波:NLP潜意识和意识
    甘超波:NLP人际界线
    甘超波:NLP表象系统
  • 原文地址:https://www.cnblogs.com/ssNiper/p/11271846.html
Copyright © 2011-2022 走看看