-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeforces_Connect.cpp
More file actions
79 lines (75 loc) · 2.11 KB
/
Copy pathCodeforces_Connect.cpp
File metadata and controls
79 lines (75 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n,x1,y11,x2,y2;
char grid[55][55];
pair<int,int> parent[55][55];
int setRank[55][55];
pair<int,int> findSet(int x, int y){
if(parent[x][y]==make_pair(x,y)) return make_pair(x,y);
return parent[x][y]=findSet(parent[x][y].first, parent[x][y].second);
}
void unionSet(int a1, int a2, int b1, int b2){
pair<int,int> a=findSet(a1,a2);
pair<int,int> b=findSet(b1,b2);
if(setRank[b.first][b.second]>setRank[a.first][a.second]) swap(a,b);
parent[b.first][b.second]=a;
if(setRank[a.first][a.second]==setRank[b.first][b.second])
setRank[a.first][a.second]++;
}
void solve(){
cin>>n>>x1>>y11>>x2>>y2;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin>>grid[i][j];
parent[i][j]={i,j};
}
}
for(int i=1; i<=n; i++){
for(int j=1; j<n; j++){
if(grid[i][j]==grid[i][j+1] and grid[i][j]=='0')
unionSet(i,j,i,j+1);
}
}
for(int i=1; i<n; i++){
for(int j=1; j<=n; j++){
if(grid[i][j]==grid[i+1][j] and grid[i][j]=='0')
unionSet(i,j,i+1,j);
}
}
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
auto x=findSet(i,j);
}
}
if(parent[x1][y11]==parent[x2][y2]){
cout<<0<<endl;
return;
}
set<pair<int,int>> stBegin,stEnd;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(parent[i][j]==parent[x1][y11])
stBegin.insert(make_pair(i,j));
if(parent[i][j]==parent[x2][y2])
stEnd.insert(make_pair(i,j));
}
}
int minCost=1e9;
for(auto it: stBegin){
for(auto itt: stEnd){
int cost=pow((itt.first-it.first),2)+pow((itt.second-it.second),2);
minCost=min(cost,minCost);
}
}
cout<<minCost<<endl;
}
signed main(){
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
optimize();
solve();
return 0;
}