迷宫最短路径 问题

/*
迷宫最短路径 问题 
*/
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct Node{
  int x, y;
  Node(int x,int y) {
    this->x = x;
    this->y = y;
  }
};
const int N = 15;
int map[9][9]= {1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1};
int d[N][N], book[N][N];
int next[][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int endx, endy;
int n, m;
void bfs(int x,int y) ;
int main() {
    int beginx, beginy;
    while (cin >> beginx >> beginy) {
      cin>> endx >> endy;
      memset(book,0,sizeof(book));
      memset(d,0,sizeof(d)); 
    n = 8, m = 8;
      bfs(beginx,beginy);
      cout << d[endx][endy] << endl;
  }
}
void bfs(int x,int y) {
  queue<Node> p;
  Node q(x,y);
  p.push(q);
  d[x][y] = 0;
  book[x][y] = 1;
  while (!p.empty()) {
    q = p.front();
    p.pop();
    if (q.x == endx && q.y == endy) return ;
    int v, u;
    for (int i = 0; i < 4; i++) {
      v = q.x + next[i][0];
      u = q.y + next[i][1];
      if (v >= 0 && v <= n && u >= 0 && u <= m && book[v][u] == 0 && map[v][u] == 0) {
        book[v][u] = 1;
        d[v][u] = d[q.x][q.y] + 1;
//        q = Node(v,u);
        p.push(Node(v,u));
      }
    }
  }
  return ;
}

 

posted @ 2017-11-07 11:39  扫地の小沙弥  阅读(228)  评论(0编辑  收藏  举报