The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.

Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.

Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.

It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.


-----Input-----

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively.

Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.


-----Output-----

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.


-----Examples-----
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3

Output
-1

Difficulty: HARD
Tags: Graph algorithms

Graph traversal

Shortest paths

Starter code:

Solutions:
import sys, os
from collections import deque
from pprint import pprint

def read_ints():
	return list(map(int, input().split()))

def read_str():
	return input().strip()
(n, m) = read_ints()
s = [read_str() for _ in range(n)]
t = [set(), set(), set()]
for i in range(n):
	for j in range(m):
		if s[i][j] in '123':
			for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
				if 0 <= ii < n and 0 <= jj < m:
					if s[ii][jj] in '123.' and s[i][j] != s[ii][jj]:
						t[int(s[i][j]) - 1].add((i, j))
						break
z = [[[1e+18] * 3 for j in range(m)] for i in range(n)]
ans = 1e+18
for root in range(3):
	q = deque()
	vi = [[False] * m for _ in range(n)]
	for (i, j) in t[root]:
		q.append((i, j, 0))
		vi[i][j] = True
		z[i][j][root] = 0
	dist = [1e+18] * 3
	dist[root] = 0
	while q:
		(i, j, d) = q.popleft()
		for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
			if 0 <= ii < n and 0 <= jj < m and (not vi[ii][jj]):
				if s[ii][jj] == '.':
					vi[ii][jj] = True
					q.append((ii, jj, d + 1))
					z[ii][jj][root] = min(z[ii][jj][root], d + 1)
				elif s[ii][jj] != s[i][j] and s[ii][jj] in '123':
					dist[int(s[ii][jj]) - 1] = min(dist[int(s[ii][jj]) - 1], d)
	ans = min(ans, sum(dist))
if ans >= 1e+18:
	print(-1)
else:
	for i in range(n):
		for j in range(m):
			if s[i][j] == '.':
				ans = min(ans, sum(z[i][j]) - 2)
	print(ans)


from collections import deque

def idx(i, j):
	return i * m + j

def solve():
	global n, m
	(n, m) = map(lambda x: int(x), input().split())
	global maxVal
	maxVal = (n * m) ** 2
	graph = [''] * (n * m)
	vrtDst = [[maxVal] * (n * m), [maxVal] * (n * m), [maxVal] * (n * m)]
	virtVertex = [deque(), deque(), deque()]
	refAsci = ord('1')
	for i in range(0, n):
		s = input()
		for j in range(0, m):
			graph[idx(i, j)] = s[j]
			indx = ord(s[j]) - refAsci
			if not 0 <= indx <= 2:
				continue
			virtVertex[indx].append((i, j))
			vrtDst[indx][idx(i, j)] = 0
	bfs01(graph, virtVertex[0], vrtDst[0])
	bfs01(graph, virtVertex[1], vrtDst[1])
	bfs01(graph, virtVertex[2], vrtDst[2])
	smallst = maxVal
	for i in range(0, n * m):
		smallst = min(smallst, vrtDst[0][i] + vrtDst[1][i] + vrtDst[2][i] - (2 if graph[i] == '.' else 0))
	print(smallst if smallst < maxVal else -1)

def bfs01(graph, queue, dist):
	while queue:
		(pi, pj) = queue.popleft()
		for (i, j) in [(pi, pj - 1), (pi, pj + 1), (pi - 1, pj), (pi + 1, pj)]:
			indx = idx(i, j)
			if not (0 <= i < n and 0 <= j < m) or graph[indx] == '#':
				continue
			isRoad = graph[indx] == '.'
			newDist = dist[idx(pi, pj)] + (1 if isRoad else 0)
			if dist[indx] > newDist:
				dist[indx] = newDist
				if isRoad:
					queue.append((i, j))
				else:
					queue.appendleft((i, j))
solve()


from collections import deque
(n, m) = input().split()
n = int(n)
m = int(m)

def idx(i, j):
	return i * m + j
max = n * m * 2
graph = ''
virtDist = [[], [], []]
virtVertex = [deque(), deque(), deque()]
virtNodesDst = [max, max, max]
code = ord('1')
for i in range(0, n):
	s = input()
	graph += s
	for j in range(0, m):
		virtDist[0].append(max)
		virtDist[1].append(max)
		virtDist[2].append(max)
		indx = ord(s[j]) - code
		if 0 > indx or indx > 2:
			continue
		virtVertex[indx].append((i, j))
		i2 = idx(i, j)
		virtDist[indx][-1] = 0

def bfs01(queue, distance):
	while queue:
		(pi, pj) = queue.popleft()
		for (i, j) in [(pi, pj - 1), (pi, pj + 1), (pi - 1, pj), (pi + 1, pj)]:
			indx = idx(i, j)
			if 0 > i or i >= n or 0 > j or (j >= m) or (graph[indx] == '#'):
				continue
			isRoad = graph[indx] == '.'
			newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
			if distance[indx] > newDistance:
				distance[indx] = newDistance
				if isRoad:
					queue.append((i, j))
				else:
					queue.appendleft((i, j))
bfs01(virtVertex[0], virtDist[0])
bfs01(virtVertex[1], virtDist[1])
bfs01(virtVertex[2], virtDist[2])
output = max
for i in range(0, n * m):
	output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2][i] - (2 if graph[i] == '.' else 0), output)
print(output if output < max else -1)


from collections import deque

def idx(i, j):
	return i * m + j

def solve():
	global n, m
	(n, m) = map(lambda x: int(x), input().split())
	global maxValue
	maxValue = (n * m) ** 2
	global graph
	graph = [''] * (n * m)
	virtDist = [[maxValue] * (n * m), [maxValue] * (n * m), [maxValue] * (n * m)]
	virtVertex = [deque(), deque(), deque()]
	refAsci = ord('1')
	for i in range(0, n):
		s = input()
		for j in range(0, m):
			graph[idx(i, j)] = s[j]
			indx = ord(s[j]) - refAsci
			if not 0 <= indx <= 2:
				continue
			virtVertex[indx].append((i, j))
			virtDist[indx][idx(i, j)] = 0
	bfs01(virtVertex[0], virtDist[0])
	bfs01(virtVertex[1], virtDist[1])
	bfs01(virtVertex[2], virtDist[2])
	output = maxValue
	for i in range(0, n * m):
		output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2][i] - (2 if graph[i] == '.' else 0), output)
	print(output if output < maxValue else -1)

def bfs01(queue, distance):
	while queue:
		(pi, pj) = queue.popleft()
		for (i, j) in [(pi, pj - 1), (pi, pj + 1), (pi - 1, pj), (pi + 1, pj)]:
			indx = idx(i, j)
			if 0 > i or i >= n or 0 > j or (j >= m) or (graph[indx] == '#'):
				continue
			isRoad = graph[indx] == '.'
			newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
			if distance[indx] > newDistance:
				distance[indx] = newDistance
				if isRoad:
					queue.append((i, j))
				else:
					queue.appendleft((i, j))
solve()