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: Wrong Answer

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest
import copy
from collections import deque

def yn(b):
    print("Yes" if b==1 else "No")
    return

def sagasu(h,w,mp,sh,sw):
    d = deque()
    x=sw
    y=sh
    d.append([y,x,0])
    while len(d)>0:
        y,x,cnt=d.popleft()
        if mp[y][x]==-2 or mp[y][x] > cnt:
            mp[y][x]=cnt
            nxt=[[y-1,x],[y+1,x],[y,x-1],[y,x+1]]
            for nx in nxt:
                y2=nx[0]
                x2=nx[1]
                if y2 < 0:
                    continue
                if y2 >= h:
                    continue
                if x2 < 0:
                    continue
                if x2 >= w:
                    continue
                if mp[y2][x2] == -2 or  mp[y2][x2] > cnt:
                    d.append([y2,x2,cnt+1])
    ret=-1
    for y in range(h):
        for x in range(w):
            ret=max(ret,mp[y][x])
    return ret
def resolve():
    readline=sys.stdin.readline

    h,w=map(int, readline().rstrip().split())

    mp=[[0 for i in range(w)] for j in range(h)]
    for y in range(h):
        ss=readline().rstrip()
        for x in range(w):
            if ss[x]=="#":
                mp[y][x]=-1 #kabe
            else:
                mp[y][x]=-2 #miti
    ans=0
    for y in range(h):
        for x in range(x):
            if mp[y][x]==-2:
                mp2=copy.deepcopy(mp)
                n=sagasu(h,w,mp2,y,x)
                ans=max(ans,n)
    print(ans)
    
    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3
#coding: utf-8
#bootcamp

from collections import defaultdict

H, W = (int(i) for i in input().split())

MAZE = []
for i in range(H):
    MAZE.append(list(input()))

INF = 10**10
d = [[INF] * H*W for _ in range(H*W)]
for i in range(H):
    for j in range(W):
        if MAZE[i][j] == '#' : continue
        node = i * W + j
        for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            ni = i + di
            nj = j + dj
            if 0 <= ni < H and 0 <= nj < W and MAZE[ni][nj] == '.':
                next_node = ni * W + nj
                d[node][next_node] = 1
                d[next_node][node] = 1

for k in range(H*W):
    for i in range(H*W):
        for j in range(H*W):
            d[i][j] =  min(d[i][j], d[i][k] + d[k][j])

ret = 0
for i in range(H*W):
    for j in range(H*W):
        if d[i][j] == INF: continue
        ret = max(ret, d[i][j])
print(ret)

Submission status: Wrong Answer

Solution code:
import queue
import numpy as np

H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
dir4 = [[-1,0],[1,0],[0,-1],[0,1]]


def solveMaze(s):
    q = queue.Queue()
    q.put([s[0],s[1],0])
    times = [[999999999 for j in range(W)] for i in range(H)]
    tmpAns = 0
    while not q.empty():
        now = q.get()
        tmpAns = max(tmpAns, now[2])
        for i in range(4):
            nextH = now[0] + int(dir4[i][0])
            nextW = now[1] + int(dir4[i][1])
            nextTime = now[2] + 1

            if nextH < 0 or nextH >= H or nextW < 0 or nextW >=W or maze[nextH][nextW] == "#" or times[nextH][nextW] <= nextTime:
                continue
            else:
                times[nextH][nextW] = nextTime
                q.put([nextH, nextW, nextTime])

    return tmpAns


ans = 0

for sH in range(H):
    for sW in range(W):
        if maze[sH][sW] == ".":
            ans = max(ans, solveMaze([sH, sW]))

print(ans)

Submission status: Wrong Answer

Solution code:
import queue
import numpy as np

H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
dir4 = [[-1,0],[1,0],[0,-1],[0,1]]


def solveMaze(s):
    q = queue.Queue()
    q.put([s[0],s[1],0])
    times = [[999999999 for j in range(W)] for i in range(H)]
    tmpAns = 0
    while not q.empty():
        now = q.get()
        tmpAns = now[2]
        for i in range(4):
            nextH = now[0] + int(dir4[i][0])
            nextW = now[1] + int(dir4[i][1])
            time = now[2] + 1

            if nextH < 0 or nextH >= H or nextW < 0 or nextW >=W or maze[nextH][nextW] == "#" or times[nextH][nextW] <= time:
                continue
            else:
                times[nextH][nextW] = time
                q.put([nextH, nextW, time])

    return tmpAns


ans = 0

for sH in range(H):
    for sW in range(W):
        if maze[sH][sW] == ".":
            ans = max(ans, solveMaze([sH, sW]))

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
H,W=map(int,input().split())

inf=1000000000
field=[]
for i in range(H):
  row=list(input())
  for j in range(len(row)):
    if row[j]=='#':row[j]=-1
    else:row[j]=inf
  field.append(row)
ans=inf

def isIn(x,y):
  if x<0 or x>=W:return False
  if y<0 or y>=H:return False
  return True
vector=[[0,1],[0,-1],[1,0],[-1,0]]
ans=0
for i in range(H):
  for j in range(W):
    l=deque([[j,i]])
    f=copy.deepcopy(field)
    f[i][j]=0
    tmp=0
    #print('--start--')
    while l:
      x,y=l.popleft()
      #print(x,y)
      #i,jを訪問
      for v in vector:
        if not isIn(x+v[1],y+v[0]):continue
        if f[y+v[0]][x+v[1]]<=tmp:continue
        f[y+v[0]][x+v[1]]=f[y][x]+1
        l.append([x+v[1],y+v[0]])
        tmp=max(f[y+v[0]][x+v[1]],tmp)
    ans=max(ans,tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
m=[]
for i in range(h):
  m.append(list(map(lambda x:int(x=="#"),list(input())))+[1,1])
m+=[[1 for i in range(w+2)]]*2
mx=0
d=[(1,0),(-1,0),(0,1),(0,-1)]
for x in range(h):
  for y in range(w):
        s=[(x,y)]
        c=-1
        v=[[0 for i in range(w)] for i in range(h)]
        while s:
          ns=[]
          for i in s:
            for j in d:
              if m[i[0]+j[0]][i[1]+j[1]] or v[i[0]+j[0]][i[1]+j[1]]:
                continue
              v[i[0]+j[0]][i[1]+j[1]]=1
              ns.append((i[0]+j[0],i[1]+j[1]))
          s=ns
          c+=1
        mx=max(mx,c)
print(mx)

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
m=[]
for i in range(h):
  m.append(list(map(lambda x:int(x=="#"),list(input())))+[1,1])
m+=[[1 for i in range(w+2)]]*2
mx=0
d=[(1,0),(-1,0),(0,1),(0,-1)]
for ax in range(h):
  for ay in range(w):
    for bx in range(h):
      for by in range(w):
        s=[(ax,ay)]
        c=1
        v=[[0 for i in range(w)] for i in range(h)]
        f=True
        while f:
          ns=[]
          for i in s:
            for j in d:
              if i[0]+j[0]==bx and i[1]+j[1]==by:
                mx=max(mx,c)
                f=False
                break
              if m[i[0]+j[0]][i[1]+j[1]] or v[i[0]+j[0]][i[1]+j[1]]:
                continue
              v[i[0]+j[0]][i[1]+j[1]]=1
              ns.append((i[0]+j[0],i[1]+j[1]))
            if not f:
              break
          s=ns
          c+=1
print(mx)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy  

H, W = map(int, input().split())
S = [list(input()) for i in range(H)]
ans = 0
queue = [[1,0],[-1,0],[0,1],[0,-1]]

def now(n,s):
    t = []
    for i in queue:
        j = n[0] + i[0]
        k = n[1] + i[1]
        if 0 <= j < H and 0 <= k < W:
            if s[j][k] == ".":
                t.append([j,k])
                s[j][k] = "#"
    return [t,s]
        

def bfs(trust, a, s):
    t = []
    for i in trust:
        tt, s = now(i,s)
        t += tt
    if len(t) == 0:
        return a
    else:
        a = a + 1
        return bfs(t, a, s)


for i in range(H):
    for j in range(W):
        s = deepcopy(S)
        if S[i][j] == ".":
            ans = max(ans, bfs([[i,j]], 0, s))
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
import sys
from collections import deque
h,w=map(int,input().split())
grid=[]
for i in range(h):
    arr=list(input())
    grid.append(arr)
    
trans=[[0,1],[0,-1],[1,0],[-1,0]]
ans=0
for a in range(h):
    for b in range(w):
        dist=[[-1]*w for _ in range(h)]
        d=deque()
        d.append((a,b))
        dist[a][b]=0

        while d:
            i,j=d.popleft()
            for s,t in trans:
                x,y=i+s,j+t
                if x>=h or x<0 or y>=w or y<0 or grid[x][y]=="#" or dist[x][y]!=-1:
                    continue
                dist[x][y]=dist[i][j]+1
                d.append((x,y))
        ans=max(ans,max(list(map(lambda z: max(z), dist))))
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
import sys
from collections import deque
h,w=map(int,input().split())
grid=[]
for i in range(h):
    arr=list(input())
    grid.append(arr)
    
trans=[[0,1],[0,-1],[1,0],[-1,0]]
ans=0
for a in range(h):
    for b in range(w):
        dist=[[-1]*w for _ in range(h)]
        d=deque()
        d.append((a,b))
        dist[a][b]=0

        while d:
            i,j=d.popleft()
            for s,t in trans:
                x,y=i+s,j+t
                if x>=h or x<0 or y>=w or y<0 or grid[x][y]=="#" or dist[x][y]!=-1:
                    continue
                dist[x][y]=dist[i][j]+1
                d.append((x,y))
        ans=max(ans,max(list(map(lambda x: max(x), dist))))
print(ans)

Submission status: Wrong Answer

Solution code:
import collections # deque, Counter
# import itertools   # accumulate, compress, permutations(nPr), combinations(nCr)
# import bisect      # bisect_left(insert位置), bisect_right(slice用)
# import math        # factorical（階乗) # hypot(距離)
# import heapq
# from fractions import gcd # Python3.5以前 # lcm（最小公倍数） = (a*b)//gcd(a,b)
# from fractions import Fraction
# from math import gcd # Python3.6以降
# --------------------------------------------------------------

H,W   = map(int,input().split())
maze  = [[None for _ in range(W)] for _ in range(H)]

for i in range(H):
    maze[i] = list(input())

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

cnt = 0

for j in range(H):
    for k in range(W):
            if maze[j][k]=='#':
                continue
            else:
                sy = j
                sx = k

                seen = [[-1 for _ in range(W)] for _ in range(H)]
                seen[sy][sx] = 0

                que  = collections.deque()  # 発見済未訪問な頂点
                que.append([sy,sx])

                while(len(que)!=0):
                    p = que.popleft()
                    for i in range(4):
                        ny = p[0] + dy[i]
                        nx = p[1] + dx[i]
                        if (ny >= 0 and nx >=0 and ny < H and nx < W and seen[ny][nx] == -1 and maze[ny][nx] != '#'):
                            seen[ny][nx] = seen[p[0]][p[1]] + 1
                            que.append([ny,nx])

                cnt = max(cnt, max(max(seen)))

print(cnt)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W=map(int,input().split())
MAP=[list(input()) for y in range(H)]

def Maze(_x, _y):
  MAP2=[[-1 for x in range(W)] for y in range(H)]
  for y in range(H):
    for x in range(W):
      if MAP[y][x]=='#':
        MAP2[y][x]=-2
  q=deque([[_x,_y]])
  MAP2[_y][_x]=0
  while q:
    xy=q.popleft()
    for d in [(0,-1),(-1,0),(0,1),(1,0)]:
      x2,y2=xy[0]+d[0],xy[1]+d[1]
      if x2<0 or y2<0 or x2>=W or y2>=H:
        continue
      if MAP2[y2][x2]==-1:
        q.append([x2,y2])
        MAP2[y2][x2]=MAP2[xy[1]][xy[0]]+1
  
  maxM=0
  for y in range(H):
    for x in range(W):
      maxM=max(maxM, MAP2[y][x])
  return maxM
  
  
ans=0
for y in range(H):
  for x in range(W):
    ans=max(ans, Maze(x,y))
print(ans)

Submission status: Wrong Answer

Solution code:
#import sys
#input=sys.stdin.readline()
#print(input)

#import pprint
h,w = map(int,input().split())
s = [list(input())for i in range(h)]
print("s")
#pprint.pprint(s,width=w*10)

visited = [[0 for i in range(w)] for j in range(h)]#sと同じ形に0を配置した表
quene = []#移動元Nowとなることができる座標のリスト
ans = 0

for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            quene.append([i,j])#スタート地点をQueneに追加
            visited[i][j]=1#スタート地点を1にする
#            print("visited")
#            pprint.pprint(visited,width=w*10)
#            print(quene)

            dy_dx=[[1,0],[-1,0],[0,1],[0,-1]]#１回に移動出来る量

            while len(quene)>=1:
                now=quene.pop(0)#queneの左端の項を取り出す
#                print(now)
                for k in range(4):
                    y=now[0]+dy_dx[k][0]#nowから移動先[x,y]へのy軸方向の移動量
                    x=now[1]+dy_dx[k][1]#nowから移動先[x,y]へのx軸方向の移動量
                    if 0<=y<h and 0<=x<w:#移動先が表を飛び出していなければOK
                        if s[y][x]!="#" and visited[y][x]==0:#移動先が壁でない、かつ行ったことがなければOK
                            visited[y][x]=visited[now[0]][now[1]]+1#移動先の値をNowの値+1にする
                            quene.append([y,x])#Queneに移動先座標を追加
#                           pprint.pprint(visited,width=w*10)
#       一つのスタート地点から幅優先探索を終わらせたら、移動量の最大値を求める
        for l in range(h):
            for m in range(w):
                ans = max(ans,visited[l][m])#これまでの最大値と今回得られた移動量の最大値を比較し、大きいほうを新しい答えにする
        visited = [[0 for i in range(w)] for j in range(h)]#visited初期化
print(ans-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
R = [[0 for j in range(W)] for i in range(H)]
ans = 0
dx = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for i in range(H):
  inp = input()
  for j in range(W):
  	if inp[j] == "#":
  	  R[i][j] = 1
for s in range(H * W):
  sh = s // W
  sw = s % W
  if R[sh][sw] == 1:
    continue
  D = [[-1 for j in range(W)] for i in range(H)]
  D[sh][sw] = 0
  d = deque([(sh, sw)])
  while len(d):
    a = d.pop()
    for k in range(4):
      hn = a[0] + dx[k][0]
      wn = a[1] + dx[k][1]
      if 0 <= hn < H and 0 <= wn < W and R[hn][wn] == 0 and D[hn][wn] == -1:
        D[hn][wn] = D[a[0]][a[1]] + 1
        ans = max(ans, D[hn][wn])
        d.appendleft((hn, wn))
  print(sh, sw)
  print(D)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
R = [[0 for j in range(W)] for i in range(H)]
ans = 0
dx = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for i in range(H):
  inp = input()
  for j in range(W):
  	if inp[j] == "#":
  	  R[i][j] = 1
for s in range(H * W):
  sh = s // W
  sw = s % W
  D = [[-1 for j in range(W)] for i in range(H)]
  D[sh][sw] = 0
  d = deque([(sh, sw)])
  while len(d):
    a = d.pop()
    for k in range(4):
      hn = a[0] + dx[k][0]
      wn = a[1] + dx[k][1]
      if 0 <= hn < H and 0 <= wn < W and R[hn][wn] == 0 and D[hn][wn] == -1:
        D[hn][wn] = D[a[0]][a[1]] + 1
        ans = max(ans, D[hn][wn])
        d.appendleft((hn, wn))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = [int(x) for x in input().split()]

field = []
for i in range(H):
    field.append(input())

conn = [[[] for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            for e in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                h, w = i + e[0], j + e[1]
                if 0 <= h < H and 0 <= w < W and field[h][w] == '.':
                    conn[i][j].append([h, w])
d = 0
for i in range(H):
    for j in range(W):
        l = 0
        q = deque([[i, j]])
        dist = [[-1 for _ in range(W)] for _ in range(H)]
        dist[i][j] = 0
        while q:
            v = q.popleft()
            for w in conn[v[0]][v[1]]:
                if dist[w[0]][w[1]] == -1:
                    q.append(w)
                    dist[w[0]][w[1]] = dist[v[0]][v[1]] + 1
                    l = dist[w[0]][w[1]]

    d = max(d, l)

print(d)

Submission status: Wrong Answer

Solution code:
from collections import deque
from copy import deepcopy

h,w = map(int,input().split())
s = [list(input()) for i in range(h)]
t = ((0,1),(1,0),(-1,0),(0,-1))
m = 0
for sy in range(h):
    for sx in range(w):
        if s[sy][sx] == "#":
            continue
        ss = deepcopy(s)
        q = deque([(0,sy,sx)])
        max_cost = 0
        my,mx = 0,0
        while(q):
            cost,y,x = q.popleft()
            max_cost = max(max_cost,cost)
            cost += 1
            for i,j in t:
                ny = y+i
                nx = x+j
                if 0 <= ny < h and 0 <= nx < w:
                    if ss[ny][nx] == ".":
                        q.append((cost,ny,nx))
                        ss[ny][nx] = "#"
        m = max(m,max_cost)
print(m)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
sy,sx = 0,0
f = False
for i,si in enumerate(s):
    if f:
        break
    for j,sij in enumerate(si):
        if sij == ".":
            sysx = i,j
            f = True
            break

t = ((0,1),(1,0),(-1,0),(0,-1))
c = 0
se = set()
while(True):
    q = deque([(0,sy,sx)])
    max_cost = 0
    my,mx = 0,0
    f = [[True]*w for i in range(h)]
    f[sy][sx] = False
    while(q):
        cost,y,x = q.popleft()
        if max_cost < cost:
            max_cost = cost
            my,mx = y,x
        f[y][x] = False
        cost += 1
        for i,j in t:
            ny = y+i
            nx = x+j
            if 0 <= ny < h and 0 <= nx < w:
                if s[ny][nx] == "." and f[ny][nx]:
                    q.append((cost,ny,nx))
    sy,sx = my,mx
    if (sy,sx) in se:
        print(max_cost)
        break
    else:
        se.add((sy,sx))
    #print(c,my,mx)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
sy,sx = 0,0
f = False
for i,si in enumerate(s):
    if f:
        break
    for j,sij in enumerate(si):
        if sij == ".":
            sysx = i,j
            f = True
            break

t = ((0,1),(1,0),(-1,0),(0,-1))
c = 0
se = set([(sy,sx)])
while(True):
    q = deque([(0,sy,sx)])
    max_cost = 0
    my,mx = 0,0
    f = [[True]*w for i in range(h)]
    f[sy][sx] = False
    while(q):
        cost,y,x = q.popleft()
        if max_cost < cost:
            max_cost = cost
            my,mx = y,x
        f[y][x] = False
        cost += 1
        for i,j in t:
            ny = y+i
            nx = x+j
            if 0 <= ny < h and 0 <= nx < w:
                if s[ny][nx] == "." and f[ny][nx]:
                    q.append((cost,ny,nx))
    sy,sx = my,mx
    if (sy,sx) in se:
        print(max_cost)
        break
    else:
        se.add((sy,sx))
    #print(c,my,mx)

Submission status: Wrong Answer

Solution code:
import math

H, W = map(int, input().split())
S = [list(map(lambda x:x == '.', input())) for _ in range(H)]

d = [[math.inf] * (H * W) for _ in range(H * W)]

def node2pos(i):
    h = i // W
    w = i % W
    return h, w

for i in range(H * W):
    for j in range(H * W):
        h1, w1 = node2pos(i)
        h2, w2 = node2pos(j)
        if (abs(h1-h2) == 1 and w1 == w2) or (abs(w1-w2) == 1 and h1 == h2):
            if S[h1][w1] and S[h2][w2]:
                d[i][j] = 1


for k in range(H * W):
    for i in range(H * W):
        for j in range(H * W):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])


ans = 0
for i in range(H * W):
    for j in range(H * W):
        if d[i][j] != math.inf:
            ans = max(ans, d[i][j])

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

def input_bordered_grid(h, w, wall):
    grid = [[wall] * (w + 2)]
    for _ in range(1, h+1):
        grid.append([wall] + [c for c in input()] + [wall])
    grid.append([wall] * (w + 2))
    return grid

h, w = map(int, input().split())
grid = input_bordered_grid(h, w, '#')

move = [(-1, 0), (1, 0), (0, -1), (0, 1)]

longest = 0
for sy in range(1, h+1):
    for sx in range(1, w+1):
        q = deque()
        visited = set()
        q.append((sy, sx, 0))
        while q:
            y, x, d = q.popleft()
            visited.add((y, x))
            longest = max(longest, d)
            for dy, dx in move:
                yy = y + dy
                xx = x + dx
                if not (yy, xx) in visited and grid[yy][xx] == '.':
                    q.append((yy, xx, d + 1))
print(longest)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

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


for i in range(h):
  for j in range(w):
        Q=deque()
        Q.append((i,j,0))
        
        if maze[i][j]=='#':
          continue

        dp=[[-1]*w for i in range(h)]

        while Q:
          p=Q.popleft()
          ans=max(ans,p[2])
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==-1:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=p[2]+1


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
m = [list(input()) for _ in range(h)]
D = [(-1, 0), (0, -1), (1, 0), (0, 1)]


def bfs(i, j):
    dist = [[0] * w for _ in range(h)]
    que = deque()
    que.append((i, j))

    while que:
        nx, ny = que.pop()
        for dx, dy in D:
            if nx + dx < 0 or ny + dy < 0 or nx + dx >= h or ny + dy >= w:
                continue
            if m[nx + dx][ny + dy] == "#":
                continue
            if dist[nx + dx][ny + dy] != 0:
                continue

            que.appendleft((nx + dx, ny + dy))
            dist[nx + dx][ny + dy] = 1 + dist[nx][ny]
    mx = 0
    for i in dist:
        mx = max(mx, max(i))
    return mx


ans = 0
for i in range(h):
    for j in range(w):
        if m[i][j] == ".":
            ans = max(ans, bfs(i, j))

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
m = [list(input()) for _ in range(h)]
D = [(-1, 0), (0, -1), (1, 0), (0, 1)]


def bfs(i, j):
    dist = [[0] * w for _ in range(h)]
    que = deque()
    que.append((i, j))

    while que:
        nx, ny = que.pop()
        for dx, dy in D:
            if nx + dx < 0 or ny + dy < 0 or nx + dx >= h or ny + dy >= w:
                continue
            if m[nx + dx][ny + dy] == "#":
                continue
            if dist[nx + dx][ny + dy] != 0:
                continue

            que.appendleft((nx + dx, ny + dy))
            dist[nx + dx][ny + dy] = 1 + dist[nx][ny]
    mx = 0
    for i in dist:
        mx = max(mx, max(i))
    return mx


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

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import permutations


h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

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


for xxx in permutations(range(h),2):
    for yyy in  permutations(range(w),2):
        i,ii=xxx[0],xxx[1]
        j,jj=yyy[0],yyy[1]


        Q=deque()
        Q.append((i,j,0))
        
        if maze[i][j]=='#' or maze[ii][jj]=='#':
          continue

        dp=[[False]*w for b in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==False:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=True


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import permutations


h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

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


for xxx in permutations(range(h),2):
    for yyy in  permutations(range(w),2):
        i,ii=xxx[0],xxx[1]
        j,jj=yyy[0],yyy[1]


        Q=deque()
        Q.append((i,j,0))
        
        if maze[i][j]=='#' or maze[ii][jj]=='#':
          continue
        
        if i==ii and j==jj:
          continue
          

        dp=[[False]*w for b in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==False:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=True


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

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


for i in range(h):
  for j in range(w):
    for ii in range(h):
      for jj in range(w):
        Q=deque()
        Q.append((i,j,0))

        dp=[[False]*w for b in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==False:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=True


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

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


for i in range(h):
  for j in range(w):
    for ii in range(i+1,h):
      for jj in range(j+1,w):
        Q=deque()
        Q.append((i,j,0))

        dp=[[False]*w for b in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==False:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=True


print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import math

H, W = list(map(int, input().split()))
S = [list(input()) for i in range(H)]

cost_max = 0
for s_y in range(H):
    for s_x in range(W):
        for g_y in range(H):
            for g_x in range(W):
                if s_y != g_y or s_x != g_x:
                    if S[s_y][s_x] == '.' and S[g_y][g_x] == '.':
                        if cost_max <= abs(s_x - g_x) + abs(s_y - g_y):
                            dist = [[math.inf] * W for i in range(H)]
                            queue = deque([(s_y, s_x)])
                            dist[s_y][s_x] = 0
                            while queue:
                                y, x = queue.popleft()
                                for i, j in [(1,0),(0,1),(-1,0),(0,-1)]:
                                    n_x, n_y = x + i, y + j
                                    if n_x >= 0 and n_y >= 0 and n_x < W and n_y < H:
                                        if dist[n_y][n_x] > dist[y][x]:
                                            if S[n_y][n_x] == '.':
                                                dist[n_y][n_x] = dist[y][x] + 1
                                                queue.append((n_y, n_x))
                            cost_max = max(cost_max, dist[g_y][g_x])

print(cost_max)

Submission status: Wrong Answer

Solution code:
import collections
H, W, *S = open(0).read().split()
H, W = [int(_) for _ in [H, W]]
G = [set() for _ in range(H * W)]
for i in range(H * W):
    x, y = divmod(i, W)
    if S[x][y] == '.':
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nx, ny = x + dx, y + dy
            if not (0 <= nx < H and 0 <= ny < W):
                continue
            if S[nx][ny] == '.':
                G[i].add(nx * W + ny)
INF = 10 ** 10
dist = [-INF] * (H * W)
for s in range(H * W):
    if len(G[s]):
        Q = collections.deque([s])
        se = set()
        while True:
            if not Q:
                break
            i = Q.popleft()
            for j in G[i]:
                if j in se:
                    continue
                se.add(j)
                k = j
                Q += [j]
        dist[k] = 0
        se = set()
        Q = collections.deque([k])
        while True:
            if not Q:
                break
            i = Q.popleft()
            if i in se:
                break
            se.add(i)
            d = dist[i]
            for j in G[i]:
                if dist[j] != -INF:
                    continue
                k = j
                dist[j] = d + 1
                Q += [j]
        print(max(dist))
        exit()

Submission status: Wrong Answer

Solution code:
import collections
H, W, *S = open(0).read().split()
H, W = [int(_) for _ in [H, W]]
G = [set() for _ in range(H * W)]
for i in range(H * W):
    x, y = divmod(i, W)
    if S[x][y] == '.':
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nx, ny = x + dx, y + dy
            if not (0 <= nx < H and 0 <= ny < W):
                continue
            if S[nx][ny] == '.':
                G[i].add(nx * W + ny)
INF = 10 ** 10
dist = [INF] * (H * W)
for s in range(H * W):
    if len(G[s]) and dist[s] == INF:
        Q = collections.deque([s])
        se = set()
        while True:
            if not Q:
                break
            i = Q.popleft()
            for j in G[i]:
                if j in se:
                    continue
                se.add(j)
                k = j
                Q += [j]
        dist[k] = 0
        se = set()
        Q = collections.deque([k])
        while True:
            if not Q:
                break
            i = Q.popleft()
            if i in se:
                break
            se.add(i)
            d = dist[i]
            for j in G[i]:
                if dist[j] != INF:
                    continue
                k = j
                dist[j] = d + 1
                Q += [j]
        print(dist[k])
        exit()