矩阵中任意多个点到某一点最短距离
作者:互联网
输入
5 5
0 0 0 0 0
8 8 8 0 0
0 0 8 0 0
8 8 8 8 0
0 0 0 0 0
4
1 1
1 5
5 1
5 5
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> direction{-1, 0, 1, 0, -1};
void dfs(queue<pair<int, int>>& points, vector<vector<int>> &grid, int m, int n
, int i, int j) {
if (i < 0 || j < 0 || i == m || j == n || grid[i][j] == 2 || grid[i][j] == 8) {
return;
}
if (grid[i][j] == 0) {
points.push({i, j});
return;
}
grid[i][j] = 2;
dfs(points, grid, m, n, i - 1, j);
dfs(points, grid, m, n, i + 1, j);
dfs(points, grid, m, n, i, j - 1);
dfs(points, grid, m, n, i, j + 1);
}
int shortestDist(vector<vector<int>> grid,int x1,int y1,int x2,int y2) {
grid[x2][y2] = 1;
int m = grid.size(), n = grid[0].size();
queue<pair<int, int>> points;
points.push({x1, y1});
grid[x1][y1] = 2;
// bfs寻找grid[x2][y2],并把过程中经过的0赋值为2
int x, y;
int level = 0;
while (!points.empty()){
++level;
int n_points = points.size();
while (n_points--) {
auto [r, c] = points.front();
points.pop();
for (int k = 0; k < 4; ++k) {
x = r + direction[k], y = c + direction[k+1];
if (x >= 0 && y >= 0 && x < m && y < n) {
if (grid[x][y] == 2) {
continue;
}
if (grid[x][y] == 8) { //障碍
continue;
}
if (grid[x][y] == 1) { //找到另一端
return level;
}
points.push({x, y});
grid[x][y] = 2;
}
}
}
}
return -1; //不通
}
int judge(vector<vector<int>> data,vector<vector<int>> &input)
{
int min = INT_MAX;
for(int i=0;i<data.size();i++)
{
for(int j=0;j<data[0].size();j++)
{
int max = 0;
for(int l = 0;l<input.size();l++)
{
if(data[i][j] == 8)
{
max = INT_MAX;
break;
}
else
{
if(i == input[l][0] && j == input[l][1])
continue;
else{
int temp = shortestDist(data,input[l][0],input[l][1],i,j);
if(temp == -1)
{
max = INT_MAX;
break;
}
if(max < temp)
max = temp;
}
}
}
cout<<"data["<<i<<"]["<<j<<"] temp is "<<max<<endl;
if(i == input[0][0] && j == input[0][1] && max == -1)
{
return -1;
}
if(min > max )
min = max;
}
}
return min;
}
int main()
{
freopen("D:\\desktop\\Leecode_dbg\\data.txt","r",stdin);
int m,n;
cin>>m>>n;
vector<vector<int>> dist(m,vector<int>(n));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>dist[i][j];
}
}
int k;
cin>>k;
vector<vector<int>> loc(k,vector<int>(2));
for(int i=0;i<k;i++)
{
int temp;
for(int j=0;j<2;j++)
{
cin>>temp;
loc[i][j] = temp -1;
}
}
cout<<judge(dist,loc)<<endl;
return 0;
}
标签:vector,temp,int,max,矩阵,points,grid,短距离,点到 来源: https://blog.csdn.net/pop541111/article/details/120677265