广度优先搜索之2个岛屿之间的最短距离
Posted Hill_LAI
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了广度优先搜索之2个岛屿之间的最短距离相关的知识,希望对你有一定的参考价值。
感觉还是深度优先搜索啊,这里使用队列实现
注意事项,循环后的变量不要重复遍历。
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <deque>
using namespace std;
vector<int> direction{-1, 0, 1, 0, -1};
void dfs(std::vector<std::vector<int>> &grid, deque<pair<int, int>> &island, int m, int n)
{
deque<pair<int, int>> temp;
temp.push_back(pair<int, int>(m, n));
while (1)
{
if (temp.empty() == true)
{
std::cout << "finish loop" << std::endl;
std::cout << "island size " << island.size() << std::endl;
break;
}
pair<int, int> item = temp.front();
int r = item.first;
int l = item.second;
std::cout << "r = " << r << " l = " << l << std::endl;
grid[r][l] = 2;
temp.pop_front();
//std::cout << "temp size " << temp.size() << std::endl;
island.push_back(item);
for (int i = 0; i < 4; i++)
{
int r_ = r + direction[i];
int l_ = l + direction[i + 1];
if (r_ >= 0 && r_ < grid.size() && l_ >= 0 && l_ < grid[0].size())
{
if (grid[r_][l_] == 1)
{
temp.push_back(pair<int, int>(r_, l_));
grid[r_][l_] = 2;
//island.push_back(pair<int, int>(r_, l_));
}
}
}
//std::cout << "emd" << std::endl;
}
return;
}
int minDistance(std::vector<std::vector<int>> &grid)
{
//find one of island
deque<pair<int, int>> points;
int m, n;
bool is_found = false;
for (int i = 0; i < grid.size(); i++)
{
if (is_found == true)
{
std::cout << "m = " << m << " n = " << n << std::endl;
break;
}
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
m = i;
n = j;
is_found = true;
break;
}
}
}
deque<pair<int, int>> island;
dfs(grid, island, m, n);
std::cout << "island size " << island.size() << std::endl;
int min_distance = 0;
while (!island.empty())
{
int p_count = island.size();
std::cout << "p_count " << p_count << std::endl;
min_distance++;
while (p_count--)
{
pair<int, int> item = island.front();
island.pop_front();
int r = item.first;
int l = item.second;
//std::cout << "r " << r << " l " << l << std::endl;
for (int i = 0; i < 4; i++)
{
int r_ = r + direction[i];
int l_ = l + direction[i + 1];
if (r_ >= 0 && r_ < grid.size() && l_ >= 0 && l_ < grid[0].size())
{
if (grid[r_][l_] == 1)
{
return min_distance - 1;
}
else if (grid[r_][l_] == 2)
{
continue;
}
else
{
//std::cout << "r_ " << r_ << " l_ " << l_ << std::endl;
island.push_back(pair<int, int>(r_, l_));
grid[r_][l_] = 2;
}
}
}
}
}
return min_distance - 1;
}
int main(int, char **)
{
std::cout << "Hello, world!\\n";
std::vector<std::vector<int>> grid = {{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 1, 0, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1}};
std::cout << "min distance " << minDistance(grid) << std::endl;
}
以上是关于广度优先搜索之2个岛屿之间的最短距离的主要内容,如果未能解决你的问题,请参考以下文章