新农上路
- 积分
- 98
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-3-9
- 最后登录
- 1970-1-1
|
简单写了一下,在 BFS 的时候记录层数。- #include <iostream>
- #include <string>
- #include <queue>
- #include <vector>
- using namespace std;
- void bfs(vector<vector<string>> &maze, int i, int j) {
- queue<pair<int, int>> current;
- queue<pair<int, int>> next;
- vector<vector<bool>> visited(maze.size(),
- vector<bool>(maze[0].size(), false));
- current.push(make_pair(i, j));
- int steps = 0;
- while (!current.empty()) {
- int row = current.front().first;
- int col = current.front().second;
- current.pop();
- visited[row][col] = true;
- if (maze[row][col] != "G" &&
- (maze[row][col] == "_" || stoi(maze[row][col]) > steps)) {
- maze[row][col] = to_string(steps);
- }
- if (row > 0 && maze[row - 1][col] != "W" && maze[row - 1][col] != "G" &&
- !visited[row - 1][col])
- next.push(make_pair(row - 1, col));
- if (row < maze.size() - 1 && maze[row + 1][col] != "W" &&
- maze[row + 1][col] != "G" && !visited[row + 1][col])
- next.push(make_pair(row + 1, col));
- if (col > 0 && maze[row][col - 1] != "W" && maze[row][col - 1] != "G" &&
- !visited[row][col - 1])
- next.push(make_pair(row, col - 1));
- if (col < maze[0].size() - 1 && maze[row][col + 1] != "W" &&
- maze[row][col + 1] != "G" && !visited[row][col + 1])
- next.push(make_pair(row, col + 1));
- if (current.empty()) {
- steps++;
- swap(current, next);
- }
- }
- }
- void closestGates(vector<vector<string>> &maze) {
- for (int i = 0; i < maze.size(); i++) {
- for (int j = 0; j < maze[0].size(); j++) {
- if (maze[i][j] == "G") bfs(maze, i, j);
- }
- }
- }
- int main(int argc, char const *argv[]) {
- vector<vector<string>> maze;
- maze.push_back(vector<string>{"_", "W", "G", "_"});
- maze.push_back(vector<string>{"_", "_", "_", "W"});
- maze.push_back(vector<string>{"_", "W", "_", "W"});
- maze.push_back(vector<string>{"G", "W", "_", "_"});
- closestGates(maze);
- for (int i = 0; i < maze.size(); i++) {
- for (int j = 0; j < maze[0].size(); j++) {
- cout << maze[i][j] << " ";
- }
- cout << endl;
- }
- }
复制代码 |
|