Tristan and Isolde, impregnable solid jade, filth, open-minded pleasure
#include<bits/bits/stdc++.h> using namespace std; class Solution { public: int shortestDistance(vector<vector<int>>& grid) { // Finally, store the result RES, the need to find a minimum value, val recursive recording layers (0, -1, -2) represents the depth int RES = INT_MAX, val = 0 , m = grid.size (), = n-Grid [ 0 ] .size (); vector<vector<int>> sum=grid; vector<vector<int>> dirs={{0,-1},{-1,0},{0,1},{1,0}}; for(int i=0;i<grid.size();++i) { for(int j=0;j<grid[i].size();++j) { // If it is a house, they begin to bfs update from the surrounding open space IF (Grid [i] [J] == 1 ) { // initialize result recording RES = INT_MAX; // dist temporarily store the distance field Vector <Vector < int >> dist = Grid; // temporarily storing address 1 (housing), and its continued expansion bfs node pressed, to ensure that all traverse Queue <pair < int , int >> Q; // pair data directly available braces Push q.push ({I, J}); // long as there have to update the housing space, to get a space to house all from the while (! q.empty ()) { // queue taking the initial value X, Y int A = q.front () First, B =. Q.front () SECOND;. // out traversal, natural eject q.pop (); // for loop when the set value, to avoid a i, could cause inadvertent re-definition repeated for ( int K = 0 ; K <dirs.size (); ++ K) { int x=a+dirs[k][0],y=b+dirs[k][1]; if(x>=0&&x<m&&y>=0&&y<n&&grid[a][b]==val) { // Representative has deepened traversing a re - Grid [X] [Y]; // open space away from the house and step dist [X] [Y] = dist [A] [B] + . 1 ; // this step is not Save too understand why a SUM [X] [Y] + = dist [X] [Y] - . 1 ; q.push({x,y}); res=min(res,sum[x][y]); } } } // BFS updated to use a new layer before the determination value less than 1 - Val; } } } return res==INT_MAX?-1:res; } };