Connect (Codeforces 1130C)
Tags: Others, dsu

Alice lives on a flat planet that can be modeled as a square grid of size $$$n \times n$$$, with rows and columns enumerated from $$$1$$$ to $$$n$$$. We represent the cell at the intersection of row $$$r$$$ and column $$$c$$$ with ordered pair $$$(r, c)$$$. Each cell in the grid is either land or water.  An example planet with $$$n = 5$$$. It also appears in the first sample test. Alice resides in land cell $$$(r_1, c_1)$$$. She wishes to travel to land cell $$$(r_2, c_2)$$$. At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $$$(r_s, c_s)$$$ and $$$(r_t, c_t)$$$ is $$$(r_s-r_t)^2 + (c_s-c_t)^2$$$.For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$. If no tunnel needs to be created, the cost is $$$0$$$.

Input: The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the width of the square grid.The second line contains two space-separated integers $$$r_1$$$ and $$$c_1$$$ ($$$1 \leq r_1, c_1 \leq n$$$) — denoting the cell where Alice resides.The third line contains two space-separated integers $$$r_2$$$ and $$$c_2$$$ ($$$1 \leq r_2, c_2 \leq n$$$) — denoting the cell to which Alice wishes to travel.Each of the following $$$n$$$ lines contains a string of $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th such line ($$$1 \leq i, j \leq n$$$) is 0 if $$$(i, j)$$$ is land or 1 if $$$(i, j)$$$ is water.It is guaranteed that $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are land.

Output: Print an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$.

Note: In the first sample, a tunnel between cells $$$(1, 4)$$$ and $$$(4, 5)$$$ should be created. The cost of doing so is $$$(1-4)^2 + (4-5)^2 = 10$$$, which is optimal. This way, Alice could walk from $$$(1, 1)$$$ to $$$(1, 4)$$$, use the tunnel from $$$(1, 4)$$$ to $$$(4, 5)$$$, and lastly walk from $$$(4, 5)$$$ to $$$(5, 5)$$$.In the second sample, clearly a tunnel between cells $$$(1, 3)$$$ and $$$(3, 1)$$$ needs to be created. The cost of doing so is $$$(1-3)^2 + (3-1)^2 = 8$$$.

Sample Inputs:
5
1 1
5 5
00001
11111
00111
00110
00110

3
1 3
3 1
010
101
010

Sample Outputs:
10

8

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 9)
from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

@bootstrap
def dfs(visited, graph, node):
    if node not in visited:
        visited.add(node)
        for neighbour in graph[node]:
            yield dfs(visited, graph, neighbour)
    yield 1
n = int(input())
(r1, c1) = map(int, input().split())
(r2, c2) = map(int, input().split())
a = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
    s = input()
    for j in range(n):
        a[i][j] = int(s[j])
graph = [[] for i in range(n * n)]
for i in range(n):
    for j in range(n):
        if i != 0:
            if a[i][j] == 0 and a[i - 1][j] == 0:
                graph[i * n + j].append(i * n - n + j)
        if i != n - 1:
            if a[i][j] == 0 and a[i + 1][j] == 0:
                graph[i * n + j].append(i * n + n + j)
        if j != 0:
            if a[i][j] == 0 and a[i][j - 1] == 0:
                graph[i * n + j].append(i * n + j - 1)
        if j != n - 1:
            if a[i][j] == 0 and a[i][j + 1] == 0:
                graph[i * n + j].append(i * n + j + 1)
visited1 = set()
dfs(visited1, graph, (r1 - 1) * n + c1 - 1)
if (r2 - 1) * n + c2 - 1 in visited1:
    print(0)
else:
    visited2 = set()
    dfs(visited2, graph, (r2 - 1) * n + c2 - 1)
    ans = 2 * n * n
    for i in visited1:
        for j in visited2:
            x1 = i % n
            y1 = i // n
            x2 = j % n
            y2 = j // n
            dis = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)
            if dis < ans:
                ans = dis
    print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10000)
n = int(input())
se1 = set()
se2 = set()
(a, b) = [int(x) for x in input().split()]
(x, y) = [int(x) for x in input().split()]
lis = []
for i in range(n):
    lis.append(input())

def dfs(x, y, f):
    if x < 0 or y < 0 or x >= len(lis) or (y >= len(lis[0])) or (lis[x][y] == '1'):
        return
    if f == 0:
        if (x, y) in se1:
            return
        se1.add((x, y))
    else:
        if (x, y) in se2:
            return
        se2.add((x, y))
    dfs(x - 1, y, f)
    dfs(x + 1, y, f)
    dfs(x, y - 1, f)
    dfs(x, y + 1, f)
dfs(a - 1, b - 1, 0)
dfs(x - 1, y - 1, 1)
ans = float('Inf')
for i in se1:
    if i in se2:
        print(0)
        exit()
    for j in se2:
        ans = min(ans, (i[0] - j[0]) ** 2 + (i[1] - j[1]) ** 2)
print(ans)

Solution (Python):
import os
import sys
import threading
from io import BytesIO, IOBase
import math
from heapq import heappop, heappush, heapify, heapreplace
from collections import defaultdict, deque, OrderedDict, Counter
from bisect import bisect_left, bisect_right
from functools import lru_cache
mod = 1000000007
mod1 = 998244353
sys.setrecursionlimit(10 ** 8)
alpha = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def primeFactors(n):
    arr = []
    l = 0
    while n % 2 == 0:
        arr.append(2)
        l += 1
        n = n // 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            arr.append(i)
            l += 1
            n = n // i
    if n > 2:
        arr.append(n)
        l += 1
    return arr

def primeFactorsSet(n):
    s = set()
    while n % 2 == 0:
        s.add(2)
        n = n // 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            s.add(i)
            n = n // i
    if n > 2:
        s.add(n)
    return s

def sieve(n):
    res = [0 for i in range(n + 1)]
    prime = []
    for i in range(2, n + 1):
        if not res[i]:
            prime.append(i)
            for j in range(1, n // i + 1):
                res[i * j] = 1
    return prime

def isPrime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i = i + 6
    return True

def countPrimesLessThanN(n):
    (seen, ans) = ([0] * n, 0)
    for num in range(2, n):
        if seen[num]:
            continue
        ans += 1
        seen[num * num:n:num] = [1] * ((n - 1) // num - num + 1)
    return ans

def gcd(x, y):
    return math.gcd(x, y)

def lcm(a, b):
    return a // gcd(a, b) * b

def isBitSet(n, k):
    res = n >> k + 1 << k
    if n >> k & 1:
        res += n & (1 << k) - 1
    return res

def popcount(x):
    x = x - (x >> 1 & 1431655765)
    x = (x & 858993459) + (x >> 2 & 858993459)
    x = x + (x >> 4) & 252645135
    x = x + (x >> 8)
    x = x + (x >> 16)
    return x & 127

def modular_exponentiation(x, y, p):
    res = 1
    x = x % p
    if x == 0:
        return 0
    while y > 0:
        if y & 1 == 1:
            res = res * x % p
        y = y >> 1
        x = x * x % p
    return res

def modInverse(A, M):
    g = gcd(A, M)
    if g == 1:
        return modular_exponentiation(A, M - 2, M)

def nCr(n, r, p):
    num = den = 1
    for i in range(r):
        num = num * (n - i) % p
        den = den * (i + 1) % p
    return num * pow(den, p - 2, p) % p

def smallestDivisor(n):
    if n % 2 == 0:
        return 2
    i = 3
    while i * i <= n:
        if n % i == 0:
            return i
        i += 2
    return n

def numOfDivisors(n):

    def pf(n):
        dic = defaultdict(int)
        while n % 2 == 0:
            dic[2] += 1
            n = n // 2
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            while n % i == 0:
                dic[i] += 1
                n = n // i
        if n > 2:
            dic[n] += 1
        return dic
    p = pf(n)
    ans = 1
    for item in p:
        ans *= p[item] + 1
    return ans

def SPF(spf, MAXN):
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, math.ceil(math.sqrt(MAXN))):
        if spf[i] == i:
            for j in range(i * i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i

def factorizationInLogN(x, spf):
    set_ = set()
    while x != 1:
        set_.add(spf[x])
        x = x // spf[x]
    return set_

class DisjointSetUnion:

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.num_sets = n

    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            (self.parent[acopy], acopy) = (a, self.parent[acopy])
        return a

    def union(self, a, b):
        (a, b) = (self.find(a), self.find(b))
        if a == b:
            return False
        if self.size[a] < self.size[b]:
            (a, b) = (b, a)
        self.num_sets -= 1
        self.parent[b] = a
        self.size[a] += self.size[b]
        return True

    def set_size(self, a):
        return self.size[self.find(a)]

    def __len__(self):
        return self.num_sets
''

def lis():
    return [int(i) for i in input().split()]

def main():
    n = int(input())
    (r1, c1) = map(int, input().split())
    (r2, c2) = map(int, input().split())
    r1 -= 1
    c1 -= 1
    r2 -= 1
    c2 -= 1
    arr = []
    for i in range(n):
        s = str(input())
        brr = []
        for j in s:
            brr.append(int(j))
        arr.append(brr)

    def rec(i, j, val):
        if i < 0 or i >= n or j < 0 or (j >= n) or (arr[i][j] == 1):
            return
        if arr[i][j] == val:
            return
        arr[i][j] = val
        rec(i + 1, j, val)
        rec(i, j + 1, val)
        rec(i - 1, j, val)
        rec(i, j - 1, val)
        return
    rec(r1, c1, 2)
    rec(r2, c2, 3)
    if arr[r1][c1] == arr[r2][c2]:
        print(0)
    else:
        brr = []
        for i in range(n):
            for j in range(n):
                if arr[i][j] == 2:
                    brr.append((i, j))
        ans = sys.maxsize
        for i in range(n):
            for j in range(n):
                if arr[i][j] == 3:
                    for (x, y) in brr:
                        ans = min(ans, (x - i) ** 2 + (y - j) ** 2)
        print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
''