Problem:


Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.



Sample input:
3 3
...
...
...


Sample output:
4

Submission status: Accepted

Solution code:
from sys import stdin
import queue

H, W = [int(x) for x in stdin.readline().rstrip().split()]
maze = [stdin.readline().rstrip().split()[0] for _ in range(H)]

ans = 0

for h in range(H):
    for w in range(W):
        if maze[h][w] == '#':
            continue
        else:
            q = queue.Queue()
            q.put((h, w, 0))
            temp_h = h
            temp_w = w
            visited = [[0] * W for _ in range(H)]
            visited[h][w] = 1
            while q.qsize() > 0:
                temp = q.get()
                temp_h = temp[0]
                temp_w = temp[1]
                temp_d = temp[2]
                ans = max(ans, temp_d)
                if temp_h + 1 < H and maze[temp_h + 1][temp_w] == '.' and visited[temp_h + 1][temp_w] == 0:
                    visited[temp_h + 1][temp_w] = 1
                    q.put((temp_h + 1, temp_w, temp_d + 1))
                if temp_h - 1 >= 0 and maze[temp_h - 1][temp_w] == '.' and visited[temp_h - 1][temp_w] == 0:
                    visited[temp_h - 1][temp_w] = 1
                    q.put((temp_h - 1, temp_w, temp_d + 1))
                if temp_w + 1 < W and maze[temp_h][temp_w + 1] == '.' and visited[temp_h][temp_w + 1] == 0:
                    visited[temp_h][temp_w + 1] = 1
                    q.put((temp_h, temp_w + 1, temp_d + 1))
                if temp_w - 1 >= 0 and maze[temp_h][temp_w - 1] == '.' and visited[temp_h][temp_w - 1] == 0:
                    visited[temp_h][temp_w - 1] = 1
                    q.put((temp_h, temp_w - 1, temp_d + 1))

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import queue

H, W = [int(x) for x in stdin.readline().rstrip().split()]
maze = [stdin.readline().rstrip().split()[0] for _ in range(H)]

ans = 0

for h in range(H):
    for w in range(W):
        if maze[h][w] == '#':
            continue
        else:
            q = queue.Queue()
            q.put((h, w, 0))
            temp_h = h
            temp_w = w
            visited = [[0] * W for _ in range(H)]
            visited[h][w] = 1
            while q.qsize() > 0:
                temp = q.get()
                temp_h = temp[0]
                temp_w = temp[1]
                temp_d = temp[2]
                ans = max(ans, temp_d)
                if temp_h + 1 < H and maze[temp_h + 1][temp_w] == '.' and visited[temp_h + 1][temp_w] == 0:
                    visited[temp_h + 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h + 1, temp_w, temp_d + 1))
                if temp_h - 1 >= 0 and maze[temp_h - 1][temp_w] == '.' and visited[temp_h - 1][temp_w] == 0:
                    visited[temp_h - 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h - 1, temp_w, temp_d + 1))
                if temp_w + 1 < W and maze[temp_h][temp_w + 1] == '.' and visited[temp_h][temp_w + 1] == 0:
                    visited[temp_h][temp_w + 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w + 1, temp_d + 1))
                if temp_w - 1 >= 0 and maze[temp_h][temp_w - 1] == '.' and visited[temp_h][temp_w - 1] == 0:
                    visited[temp_h][temp_w - 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w - 1, temp_d + 1))

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import queue

H, W = [int(x) for x in stdin.readline().rstrip().split()]
maze = [stdin.readline().rstrip().split()[0] for _ in range(H)]

ans = 0

for h in range(H):
    for w in range(W):
        if maze[h][w] == '#':
            continue
        else:
            q = queue.Queue()
            q.put((h, w, 0))
            visited = [[0] * W for _ in range(H)]
            visited[h][w] = 1
            while q.qsize() > 0:
                temp = q.get()
                temp_h = temp[0]
                temp_w = temp[1]
                temp_d = temp[2]
                ans = max(ans, temp_d)
                if temp_h + 1 < H and maze[temp_h + 1][temp_w] == '.' and visited[temp_h + 1][temp_w] == 0:
                    visited[temp_h + 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h + 1, temp_w, temp_d + 1))
                if temp_h - 1 >= 0 and maze[temp_h - 1][temp_w] == '.' and visited[temp_h - 1][temp_w] == 0:
                    visited[temp_h - 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h - 1, temp_w, temp_d + 1))
                if temp_w + 1 < W and maze[temp_h][temp_w + 1] == '.' and visited[temp_h][temp_w + 1] == 0:
                    visited[temp_h][temp_w + 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w + 1, temp_d + 1))
                if temp_w - 1 >= 0 and maze[temp_h][temp_w - 1] == '.' and visited[temp_h][temp_w - 1] == 0:
                    visited[temp_h][temp_w - 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w - 1, temp_d + 1))

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import queue

H, W = [int(x) for x in stdin.readline().rstrip().split()]
maze = [stdin.readline().rstrip().split()[0] for _ in range(H)]

ans = 0

for h in range(H):
    for w in range(W):
        if maze[h][w] == '#':
            continue
        else:
            q = queue.Queue()
            q.put((h, w, 0))
            visited = [[-1] * W for _ in range(H)]
            visited[h][w] = 0
            while q.qsize() > 0:
                temp = q.get()
                temp_h = temp[0]
                temp_w = temp[1]
                temp_d = temp[2]
                ans = max(ans, visited[temp_h][temp_w])
                if temp_h + 1 < H and maze[temp_h + 1][temp_w] == '.' and visited[temp_h + 1][temp_w] < 0:
                    visited[temp_h + 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h + 1, temp_w, temp_d + 1))
                if temp_h - 1 >= 0 and maze[temp_h - 1][temp_w] == '.' and visited[temp_h - 1][temp_w] < 0:
                    visited[temp_h - 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h - 1, temp_w, temp_d + 1))
                if temp_w + 1 < W and maze[temp_h][temp_w + 1] == '.' and visited[temp_h][temp_w + 1] < 0:
                    visited[temp_h][temp_w + 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w + 1, temp_d + 1))
                if temp_w - 1 >= 0 and maze[temp_h][temp_w - 1] == '.' and visited[temp_h][temp_w - 1] < 0:
                    visited[temp_h][temp_w - 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w - 1, temp_d + 1))

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import queue

H, W = [int(x) for x in stdin.readline().rstrip().split()]
maze = [stdin.readline().rstrip().split()[0] for _ in range(H)]

ans = 0

for h in range(H):
    for w in range(W):
        if maze[h][w] == '#':
            continue
        else:
            q = queue.Queue()
            q.put((h, w))
            visited = [[-1] * W for _ in range(H)]
            visited[h][w] = 0
            while q.qsize() > 0:
                temp = q.get()
                temp_h = temp[0]
                temp_w = temp[1]
                ans = max(ans, visited[temp_h][temp_w])
                if temp_h + 1 < H and maze[temp_h + 1][temp_w] == '.' and visited[temp_h + 1][temp_w] < 0:
                    visited[temp_h + 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h + 1, temp_w))
                if temp_h - 1 >= 0 and maze[temp_h - 1][temp_w] == '.' and visited[temp_h - 1][temp_w] < 0:
                    visited[temp_h - 1][temp_w] = visited[temp_h][temp_w] + 1
                    q.put((temp_h - 1, temp_w))
                if temp_w + 1 < W and maze[temp_h][temp_w + 1] == '.' and visited[temp_h][temp_w + 1] < 0:
                    visited[temp_h][temp_w + 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w + 1))
                if temp_w - 1 >= 0 and maze[temp_h][temp_w - 1] == '.' and visited[temp_h][temp_w - 1] < 0:
                    visited[temp_h][temp_w - 1] = visited[temp_h][temp_w] + 1
                    q.put((temp_h, temp_w - 1))

print(ans)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    h,w = LI()
    a = [[c=='#' for c in S()] for _ in range(h)]

    def search(s):
        d = collections.defaultdict(lambda: inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for di,dj in dd:
                ni = u[0] + di
                nj = u[1] + dj
                if ni < 0 or ni >= h or nj < 0 or nj >= w or a[ni][nj]:
                    continue
                uv = (ni,nj)
                if v[uv]:
                    continue
                vd = k + 1
                if d[uv] > vd:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return d

    r = 0
    for i in range(h):
        for j in range(w):
            if a[i][j]:
                continue
            d = search((i,j))
            t = max(d.values())
            if r < t:
                r = t

    return r


print(main())

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
grid=[None]*H
for i in range(H):
  grid[i]=input()

ans=0
from collections import deque
for i in range(H):
  for j in range(W):
    q=deque()
    q.append([i,j,0])
    seen=[[False for j in range(W)] for i in range(H)]
    while q:
      node=q.popleft()
      y=node[0]
      x=node[1]
      dist=node[2]
      if grid[y][x]=="#":
        continue
      if seen[y][x]:
        continue
      seen[y][x]=True
      if dist>ans:
        ans=dist
      cases=((0,1),(0,-1),(1,0),(-1,0))
      for c in cases:
        if 0<=y+c[0]<H and 0<=x+c[1]<W:
          q.append([y+c[0],x+c[1],dist+1])
      
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

H, W = list(map(int, input().split()))

tbl = np.zeros([H, W], dtype=np.uint8)
for col in tbl:
	x = input().replace('.', '1').replace('#', '0')
	col[:] = list(x)

def func(y,x):
    dp = np.ones([H, W]) * np.inf
    data = tbl.copy()
    data[y,x] = 0
    dp[y,x] = 0

    que = [[y,x]]

    def move(i, j, m, n):
        if m<0 or n<0 or m>=H or n>=W:
            return

        if data[m, n] == 1:
            data[m, n] = 0
            dp[m, n] = min(dp[i, j] + 1, dp[m, n])
            que.append([m, n])

    while len(que) > 0:
        i, j = que.pop(0)
        move(i,j,i-1,j)
        move(i,j,i+1,j)
        move(i,j,i,j-1)
        move(i,j,i,j+1)
       
    return dp[dp != np.inf].max() 

ans = 0
for i in range(H):
    for j in range(W):
        if tbl[i,j] == 0:
            continue
        
        num = func(i, j)    
        if num != np.inf:
            ans = max(ans, num)
            if ans == H + W - 2:
                break

if ans == np.inf:
	ans = 0
print(int(ans))

Submission status: Accepted

Solution code:
import heapq
INFTY = 10**3
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
dist = {(i,j):{(k,l):INFTY for k in range(H) for l in range(W)} for j in range(W) for i in range(H)}
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            hist = {(k,l):0 for k in range(H) for l in range(W)}
            heap = [(0,i,j)]
            dist[(i,j)][(i,j)]= 0
            hist[(i,j)] = 1
            while heap:
                d,k,l = heapq.heappop(heap)
                if d>dist[(i,j)][(k,l)]:continue
                hist[(k,l)] = 1
                if l+1<W and S[k][l+1]=="." and hist[(k,l+1)]==0:
                    if dist[(i,j)][(k,l+1)]>d+1:
                        dist[(i,j)][(k,l+1)] = d+1
                        heapq.heappush(heap,(d+1,k,l+1))
                if l-1>-1 and S[k][l-1]=="." and hist[(k,l-1)]==0:
                    if dist[(i,j)][(k,l-1)]>d+1:
                        dist[(i,j)][(k,l-1)]=d+1
                        heapq.heappush(heap,(d+1,k,l-1))
                if k+1<H and S[k+1][l]=="." and hist[(k+1,l)]==0:
                    if dist[(i,j)][(k+1,l)]>d+1:
                        dist[(i,j)][(k+1,l)]=d+1
                        heapq.heappush(heap,(d+1,k+1,l))
                if k-1>-1 and S[k-1][l]=="." and hist[(k-1,l)]==0:
                    if dist[(i,j)][(k-1,l)]>d+1:
                        dist[(i,j)][(k-1,l)]=d+1
                        heapq.heappush(heap,(d+1,k-1,l))
dmax = 0
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                if dist[(i,j)][(k,l)]<INFTY:
                    dmax = max(dmax,dist[(i,j)][(k,l)])
print(dmax)

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
h, w = map(int, input().split())
g = []
for i in range(h):
    g.append(input())

move = ((0, 1), (1, 0), (-1, 0), (0, -1))
ans = 0

for start in  [[i, j] for i in range(h) for j in range(w)]:
    if g[start[0]][start[1]] == "#":
        continue
    dp = [[0 for i in range(w)] for i in range(h)]
    pre = [-1, -1]
    cur = start
    cnt = 0
    queue = deque([[cur, pre, cnt]])
    while queue:
        cur, pre, cnt = queue.popleft()
        c_x, c_y = cur
        if g[c_x][c_y] == '#':
          continue
        if not dp[c_x][c_y] or (dp[c_x][c_y] and dp[c_x][c_y] > cnt):
            dp[c_x][c_y] = cnt

            for x, y in move:
                next = [cur[0] + x, cur[1] + y]
                if next == start:
                    continue
                if next != pre and next[0] >= 0 and next[0] < h and next[1] >= 0 and next[1] < w:
                    queue.append([next, cur, cnt + 1])
    ans= max(max([dp[i][j] for i in range(h) for j in range(w)]), ans)


print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from copy import deepcopy

h, w = map(int, input().split())
INF = float("inf")
s = [list(map(lambda x: -1 if x == "#" else INF, input())) for _ in range(h)]

ans = 0

def bfs(init_y, init_x, s):
    vect = ((-1, 0), (0, -1), (1, 0), (0, 1))
    if s[init_y][init_x] == -1: return 0
    s[init_y][init_x] = 0
    q = deque([(init_y, init_x)])
    while q:
        y, x = q.popleft()
        for dy, dx in vect:
            ny, nx = y + dy, x + dx
            if ny < 0 or ny >= h or nx < 0 or nx >= w or s[ny][nx] != INF: continue
            s[ny][nx] = s[y][x] + 1
            q.append((ny, nx))
    return max(map(max, s))

for i in range(h):
    for j in range(w):
        ans = max(ans, bfs(i, j, deepcopy(s)))

print(ans)

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, text, pos):
        self.text = text
        self.pos = pos
        self.next_nodes = []

    def add_next(self, node):
        self.next_nodes.append(node)


def all_pats():
    pat = []
    for i in range(H):
        for j in range(W):
            pat.append((i, j))
    return pat


def dfs(start):
    queue = []
    queue.append(start)
    count = dict()
    count[start.pos] = 0

    while True:
        if not queue:
            break
        node = queue[0]
        queue = queue[1:]

        for next_node in node.next_nodes:
            if next_node.pos in count:
                continue
            count[next_node.pos] = count[node.pos] + 1
            queue.append(next_node)
    return max(count.values())


H, W = [int(x) for x in input().split(" ")]
nodes = dict()
for i in range(H):
    for j, text in enumerate(input()):
        nodes[(i, j)] = Node(text, (i, j))


for i in range(H):
    for j in range(W):
        node = nodes[(i, j)]
        if node.text == "#":
            continue
        for pos in [(i-1, j), (i, j-1), (i+1, j), (i, j+1)]:
            if 0 <= pos[0] <= H-1 and 0 <= pos[1] <= W-1 and nodes[pos].text == ".":
                node.add_next(nodes[pos])


all_pats = all_pats()

counts = []
for start in all_pats:
    counts.append(dfs(nodes[start]))

print(max(counts))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input()for _ in range(h)]

ans=0
dx = [1,0,-1,0]
dy = [0,1,0,-1] 
import queue
for si in range(h):
	for sj in range(w):
		if s[si][sj] == "#":
			continue
		dist = [[-1 for a in range(w)]for b in range(h)]
		q = queue.Queue()
		q.put([si,sj])
		dist[si][sj]=0
		while not q.empty():
			nowi,nowj = q.get()
			for ne in range(4):
				nexti,nextj = nowi+dx[ne],nowj+dy[ne]
				if nexti<0 or nexti>=h or nextj<0 or nextj>=w:
					continue
				if dist[nexti][nextj] != -1 or s[nexti][nextj]=="#":
					continue
				dist[nexti][nextj] = dist[nowi][nowj]+1
				q.put([nexti,nextj])
				ans = max(ans,dist[nexti][nextj])
print(ans)

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = int(h), int(w)
    s = ["#" * (w + 2)] + ["#" + _s + "#" for _s in s] + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]

    def n(q, cx, cy):
        for x, y in d:
            nx = cx + x
            ny = cy + y
            if s[nx][ny] == ".":
                q.append((nx, ny, cx, cy))

    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        q = list()
        n(q, _h, _w)
        if len(q) > 2:
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            n(q, cx, cy)
        for i, j in product(range(1, h + 1), range(1, w + 1)):
            ans = max(ans, c[i][j] * (s[i][j] == "."))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = int(h), int(w)
    s = ["#" * (w + 2)] + ["#" + _s + "#" for _s in s] + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        q = list()
        for x, y in d:
            if s[_h + x][_w + y] == ".":
                q.append((_h + x, _w + y, _h, _w))
        if len(q) > 2:
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            for x, y in d:
                nx = cx + x
                ny = cy + y
                if s[nx][ny] == ".":
                    q.append((nx, ny, cx, cy))
        for i, j in product(range(1, h + 1), range(1, w + 1)):
            ans = max(ans, c[i][j] * (s[i][j] == "."))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = map(int, [h, w])
    s = ["#" * (w + 2)] + ["#" + _s + "#" for _s in s] + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        q = list()
        for x, y in d:
            if s[_h + x][_w + y] == ".":
                q.append((_h + x, _w + y, _h, _w))
        if len(q) > 2:
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            for x, y in d:
                if s[cx + x][cy + y] == ".":
                    q.append((cx + x, cy + y, cx, cy))
        for i, j in product(range(1, h + 1), range(1, w + 1)):
            ans = max(ans, c[i][j] * (s[i][j] == "."))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = map(int, [h, w])
    s = ["#" * (w + 2)] + ["#" + _s + "#" for _s in s] + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        q = list()
        for x, y in d:
            if s[_h + x][_w + y] == ".":
                q.append((_h + x, _w + y, _h, _w))
        if len(q) > 2:
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            for x, y in d:
                if s[cx + x][cy + y] == ".":
                    q.append((cx + x, cy + y, cx, cy))
        ans = max(
            ans,
            *(c[i][j] * (s[i][j] == ".") for i, j in product(range(1, h + 1), range(1, w + 1))))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = map(int, [h, w])
    s = ["#" + _s + "#" for _s in s]
    s = ["#" * (w + 2)] + s + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        q = list()
        for x, y in d:
            if s[_h + x][_w + y] == ".":
                q.append((_h + x, _w + y, _h, _w))
        if len(q) > 2:
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            for x, y in d:
                nx = cx + x
                ny = cy + y
                if s[nx][ny] == ".":
                    q.append((nx, ny, cx, cy))
        for i, j in product(range(1, h + 1), range(1, w + 1)):
            ans = max(ans, c[i][j] * (s[i][j] == "."))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
from itertools import product


def solve(string):
    h, w, *s = string.split()
    h, w = map(int, [h, w])
    s = ["#" + _s + "#" for _s in s]
    s = ["#" * (w + 2)] + s + ["#" * (w + 2)]
    ans = 0
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for _h, _w in product(range(1, h + 1), range(1, w + 1)):
        if s[_h][_w] == "#":
            continue
        c = [[h * w] * (w + 2) for _ in range(h + 2)]
        c[_h][_w] = 0
        q = list()
        for x, y in d:
            if s[_h + x][_w + y] == ".":
                q.append((_h + x, _w + y, _h, _w))
        if len(q) > 2:
            continue
        while q:
            cx, cy, px, py = q.pop()
            if c[px][py] + 1 >= c[cx][cy]:
                continue
            c[cx][cy] = c[px][py] + 1
            for x, y in d:
                nx = cx + x
                ny = cy + y
                if s[nx][ny] == ".":
                    q.append((nx, ny, cx, cy))
        for i, j in product(range(1, h + 1), range(1, w + 1)):
            ans = max(ans, c[i][j] * (s[i][j] == "."))
    return str(ans)


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]

def route(l):
  routeout = []
  if l[0] > 0:
    if sc[l[1]][l[0]-1] == '.':
      routeout.append([l[0]-1, l[1]])
  if l[0] < w-1:
    if sc[l[1]][l[0]+1] == '.':
      routeout.append([l[0]+1, l[1]])
  if l[1] > 0:
    if sc[l[1]-1][l[0]] == '.':
      routeout.append([l[0], l[1]-1])
  if l[1] < h-1:
    if sc[l[1]+1][l[0]] == '.':
      routeout.append([l[0], l[1]+1])
  return routeout

def f(linl, out):
  nextxy = []
  for l in linl:
    nextxy += route(l)
    for ll in route(l):
      sc[ll[1]][ll[0]] = '#'
  if len(nextxy)>0:
    return f(nextxy, out+1)
  else:
    return out
  
r = set()
for i in range(h):
  for j in range(w):
    if s[i][j] == '.':
      sc = [[l for l in ll] for ll in s]
      sc[i][j] = '#'
      r.add(f([[j, i]], 0))
print(max(r))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
ar = []
for i in range(n):
    ar.append(list(input()))

dx = [1, -1, 0, 0]
dy = [0, 0, -1, 1]
res  = 0


for i in range(n):
    for j in range(m):
        if ar[i][j] == '.':
            vis = [[-1] * m for k in range(n)]
            queue = [i, j]
            vis[i][j] = 0
            while len(queue):
                x = queue.pop(0)
                y = queue.pop(0)
                for k in range(4):
                    x1 = x + dx[k]
                    y1 = y + dy[k]
                    if 0 <= x1 < n and 0 <= y1 < m and ar[x1][y1] == '.' and vis[x1][y1] == -1:
                        vis[x1][y1] = vis[x][y] + 1
                        res = max(res, vis[x1][y1])
                        queue.append(x1)
                        queue.append(y1)

print(res)

Submission status: Accepted

Solution code:
h,w=map(int, input().split())
g={}
for i in range(h):
    l=input()
    length=len(l)
    for j,x in enumerate(l):
        if x == '#':
            continue
        pos=length*i+j
        g[pos]=[]
        if pos-1 in g.keys() and pos % length != 0:
            g[pos-1].append(pos)
            g[pos].append(pos-1)
        if pos-length in g.keys():
            g[pos-length].append(pos)
            g[pos].append(pos-length)

counts = []
for i in g.keys():
    l = [i]
    done = []
    count = 0
    while len(l):
        for _ in range(len(l)):
            x = l.pop(0)
            done.append(x)
            for y in g[x]:
                if y in done:
                    continue
                if y in l:
                    continue
                l.append(y)
        count=count+1
    counts.append(count)
print(max(map(lambda x: x-1, counts)))

Submission status: Accepted

Solution code:
import numpy as np
from copy import deepcopy
temp=list(map(int, input().split()))
R=temp[0]
C=temp[1]

color=np.zeros((R,C)).astype(int)

for i in range(R):
  temp=input()
  a=np.zeros(C).astype(int)
  for j in range(C):
      if temp[j]=='#':
        a[j]=1
      else:
        a[j]=0
  color[i]=a
  
def Adj(u):
  adj=[]
  for v in [(u[0]-1,u[1]),(u[0]+1,u[1]),(u[0],u[1]-1),(u[0],u[1]+1)]:
      if v[0]>=0 and v[0]<R and v[1]>=0 and v[1]<C:
        adj.append(v)
  return adj  

def BFS(s,c,d):
  Q=[s]
  while Q !=[]:
    u=Q[0]
    del Q[0]
    for v in Adj(u):  
      if c[v[0],v[1]]==0:
        c[v[0],v[1]]=1
        d[v[0],v[1]]=d[u[0],u[1]]+1
        Q.append(v)
        
def main():
  ma=0
  for sx in range(R):
    for sy in range(C):
      if color[sx,sy]==0:
        d=np.zeros((R,C)).astype(int)
        c=deepcopy(color)
        c[sx,sy]=1
        BFS((sx,sy),c,d)
        ma=max(np.max(d),ma)
  print(ma)

main()

Submission status: Accepted

Solution code:
import numpy as np
from copy import deepcopy
temp=list(map(int, input().split()))
R=temp[0]
C=temp[1]

color=np.zeros((R,C)).astype(int)

for i in range(R):
  temp=input()
  a=np.zeros(C).astype(int)
  for j in range(C):
      if temp[j]=='#':
        a[j]=1
      else:
        a[j]=0
  color[i]=a
  
def Adj(u):
  adj=[]
  for v in [(u[0]-1,u[1]),(u[0]+1,u[1]),(u[0],u[1]-1),(u[0],u[1]+1)]:
      if v[0]>=0 and v[0]<R and v[1]>=0 and v[1]<C:
        adj.append(v)
  return adj  

def BFS(s,c,d):
  ma=0
  Q=[s]
  while Q !=[]:
    u=Q[0]
    del Q[0]
    if d[u[0],u[1]]>ma:
      ma=d[u[0],u[1]]
    for v in Adj(u):  
      if c[v[0],v[1]]==0:
        c[v[0],v[1]]=1
        d[v[0],v[1]]=d[u[0],u[1]]+1
        Q.append(v)
  return ma
        
def main():
  ma=0
  for sx in range(R):
    for sy in range(C):
      if color[sx,sy]==0:
        d=np.zeros((R,C)).astype(int)
        c=deepcopy(color)
        c[sx,sy]=1
        ma=max(BFS((sx,sy),c,d),ma)
  print(ma)

main()