K - Maze

It is to find the shortest path to a maze, but the difference is to put the path output

Ideas: the first to write a normal BFS, but more than join an array, each point on the record a point, reaching the last point and then search for DFS upward path

#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;
}

 

Guess you like

Origin www.cnblogs.com/ssNiper/p/11271846.html