题解 | #走迷宫#

走迷宫

http://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64

广度优先BFS

#include <iostream>
#include <cstring>
#include <string>
#include <queue>

int main(int argc, char *argv[]) {
  int dx[4] = {1, -1, 0, 0};  // 两种对应下标搭配四个方向
  int dy[4] = {0, 0, -1, 1};  // BFS优先邻近点
  std::queue<std::pair<int, int>> point_queue;  // BFS先访问的点,其邻近点也先访问
  int n, m, start_x, start_y, end_x, end_y;
  
  std::cin >> n >> m;
  std::cin >> start_x >> start_y >> end_x >> end_y;
  
  char net[n+1][m+1];  
  int visited[n+1][m+1];   
  
  memset(net, 0, sizeof(net));   // 网,下标从1开始
  memset(visited, -1, sizeof(visited));   // 未访问为-1
  
  for (int i = 1; i <= n; i++) {  // 从(1,1)开始存储
    std::string temp;
    std::cin >> temp;
    std::memcpy(net[i]+1, temp.c_str(), temp.size());
  }
  
  point_queue.push({start_x, start_y});
  visited[start_x][start_y] = 0;  // 起点改变其访问状态,顺便充当计数器
  
  while (point_queue.size()) { // 邻近点加入队列,一直访问邻近点直到无路时栈空
    auto cur_point = point_queue.front();
    point_queue.pop();

    for (int i = 0; i < 4; i++) {
      int x = cur_point.first + dx[i], y = cur_point.second + dy[i];
      // 四个邻近点依次访问
      if (x >= 1 && x <= n && y >= 1 && y <= m && visited[x][y] == -1 && net[x][y] == '.') {
        visited[x][y] = visited[cur_point.first][cur_point.second] + 1;   // 标记访问并且计数
        point_queue.push({x, y});      // 邻近点入队(先访问先入)
      }
    }
  }
  
  std::cout << visited[end_x][end_y] << std::endl;   // 初值为-1,没有访问到则为-1
  
  return 0;
}
全部评论
BFS 考虑所有方向。先访问的结点其邻近节点也优先访问,因此使用队列。
点赞 回复 分享
发布于 2022-04-13 01:30

相关推荐

03-16 22:00
武汉大学 C++
幸福的小熊猫想要offer:我阿里投的 c++岗,面试官说自己是做 java 的,c++这辈子才有了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客企业服务