Leetcode-934 Shortest Bridge(最短的桥)

 1 class Solution
 2 {
 3     private:
 4         vector<pair<int,int>> graphA,graphB;
 5         int colSize;
 6         int mark;
 7         const int xList[4] {1,0,0,-1};
 8         const int yList[4] {0,1,-1,0};
 9     public:
10         bool isValid(int x,int y)
11         {
12             return (x<colSize && y<colSize && x>=0 && y >= 0);
13         }
14         void floodFill(vector<vector<int>>& A,int x,int y)
15         {
16             A[x][y] = mark;
17             if(mark == 2)
18             {
19                 graphA.push_back({x,y});
20             }
21             else
22             {
23                 graphB.push_back({x,y});
24             }
25             for(int i = 0;i < 4;i ++)
26             {
27                 int newX = x+xList[i];
28                 int newY = y+yList[i];
29                 if(isValid(newX,newY) && A[newX][newY] == 1)
30                 {
31                     floodFill(A,newX,newY);
32                 }
33             }
34         }
35         int shortestBridge(vector<vector<int>>& A)
36         {
37             colSize = A.size();
38             mark = 2;
39             for(int i = 0;i < A.size();i ++)
40             {
41                 for(int j = 0;j < A[i].size();j ++)
42                 {
43                     if(A[i][j] == 1)
44                     {
45                         floodFill(A,i,j);
46                         mark ++;
47                     }
48                 } 
49             }
50 
51             int result = 3939;
52             for(auto p1:graphA)
53             {
54                 for(auto p2:graphB)
55                 {
56                     if(abs(p1.first-p2.first)+abs(p1.second-p2.second) < result)
57                     {
58                         result = abs(p1.first-p2.first)+abs(p1.second-p2.second);
59                     }
60                 }
61             }
62             return result-1;
63         }
64 };

 

posted @ 2018-11-06 19:10  Asurudo  阅读(683)  评论(0编辑  收藏  举报