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:
h, w = map(int, input().split())
#s = [['#' for _ in range(w+2)]] + [list('#' + input() + '#') for _ in range(h)] + [['#' for _ in range(w+2)]]
s = [list(input()) for _ in range(h)]

n = h * w
m = [[float('inf') for _ in range(n)] for _ in range(n)]

#for x in m: print(x)
for i in range(h):
    for j in range(w-1):
        if s[i][j] == '.':
            if s[i][j+1] == '.':
                m[i * w + j][i * w + j + 1] = 1
                m[i * w + j + 1][i * w + j] = 1

for i in range(h-1):
    for j in range(w):
        if s[i][j] == '.':
            if s[i+1][j] == '.':
                m[i*w+j][(i+1)*w+j] = 1
                m[(i+1)*w+j][i*w+j] = 1

def warshall_floyd(d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

m = warshall_floyd(m)
ans = 0
for i in range(n):
    for j in range(n):
        if m[i][j] != float('inf'):
            ans = max(ans, m[i][j])

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def main():
    inf=1000
    h,w=MI()
    ss=[[c=="#" for c in input()] for _ in range(h)]
    n=h*w
    dist=[[inf]*n for _ in range(n)]
    #for i in range(n):dist[i][i]=0
    to=defaultdict(list)
    kill=[False]
    for i in range(h):
        for j in range(w):
            if ss[i][j]:continue
            ij=w*i+j
            for ni,nj in [(i+1,j),(i,j+1),(i-1,j),(i,j-1)]:
                if ni<0 or nj<0 or ni>=h or nj>=w:continue
                if ss[ni][nj]:continue
                nij=w*ni+nj
                to[ij].append(nij)
                to[nij].append(ij)
                dist[nij][ij]=dist[ij][nij]=1
    for j in range(n):
        for i in range(n):
            for k in range(n):
                d=dist[i][j]+dist[j][k]
                if d>=inf:continue
                if d<dist[i][k]:dist[i][k]=d
    #p2D(dist)
    mx=0
    for i in range(n):
        for j in range(n):
            d=dist[i][j]
            if d==inf:continue
            if d>mx:mx=d
    print(mx)

main()

Submission status: Wrong Answer

Solution code:
import heapq
import itertools


def astar(init_pos, goal):
    passed_list = [init_pos]
    init_score = distance(passed_list) + heuristic(init_pos)
    checked = {init_pos: init_score}
    searching_heap = []
    heapq.heappush(searching_heap, (init_score, passed_list))
    while len(searching_heap) > 0:
        score, passed_list = heapq.heappop(searching_heap)
        last_passed_pos = passed_list[-1]
        if last_passed_pos == goal:
            return passed_list
        for pos in nexts(last_passed_pos):
            new_passed_list = passed_list + [pos]
            pos_score = distance(new_passed_list) + heuristic(pos)
            if pos in checked and checked[pos] <= pos_score:
                continue
            checked[pos] = pos_score
            heapq.heappush(searching_heap, (pos_score, new_passed_list))

    return []

if __name__ == "__main__":
    h, w = map(int, input().split())
    maze = [input() for j in range(h)]

    init = (0,0)
    goal = (h-1,w-1)

    def nexts(pos):
        ''' 探索中の座標から八方の座標を計算するジェネレーター'''
        wall = "#"

        # for a, b in itertools.product([' + 1', ' - 1', ''], repeat=2):
        for a, b in [["+1",""], ["-1", ""], ["", "+1"], ["", "-1"]]:
            if a or b:
                if 0 <= eval('pos[0]' + a) < h and 0 <= eval('pos[1]' + b) < w and maze[eval('pos[0]' + a)][eval('pos[1]' + b)] != wall:
                    yield (eval('pos[0]' + a), eval('pos[1]' + b))

    def heuristic(pos):
        ''' 探索中の座標からゴールまでの最短距離のスコア '''
        return ((pos[0] - goal[0]) ** 2 + (pos[1] - goal[1]) ** 2) ** 0.5

    def distance(path):
        ''' スタートから探索中の座標までの距離のスコア '''
        return len(path)

    def render_path(path):
        ''' 結果の出力 '''
        buf = [[ch for ch in l] for l in maze]

        for pos in path[1:-1]:
            buf[pos[0]][pos[1]] = "*"

        buf[path[0][0]][path[0][1]] = "s"
        buf[path[-1][0]][path[-1][1]] = "g"
        return ["".join(l) for l in buf]

    path1 = astar(init, goal)

    init = (h-1,0)
    goal = (0,w-1)

    path2 = astar(init, goal)

    if len(path1) > 0 and len(path2) > 0:
        print(max(len(path1), len(path2)) - 1)
    elif len(path1) > 0:
        print(len(path1)-1)
    elif len(path2) > 0:
        print(len(path2) - 1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import queue

row, col = map(int, input().split(' '))
maze = [list(input()) for _ in range(row)]

                
def BPS(si, sj):
    global done
    done = [[0 for _ in range(col)] for _ in range(row)]
    q = queue.Queue()
    q.put((si, sj, 0))
    around = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    maxv = 0
    while not q.empty():
        i, j, cnt = q.get()
        maxv = max(maxv, cnt)
        done[i][j] = 1
        for ar in around:
            di, dj = ar[0], ar[1]
            i_n, j_n = i + di, j + dj
            if (i_n >= 0 and i_n < row and j_n >= 0 and j_n < col) == False:
                continue
            if maze[i_n][j_n] == '#':
                continue
            if done[i_n][j_n] == 1:
                continue
            if done[i_n][j_n] == 2:
                continue
            q.put((i_n, j_n, cnt + 1))
            done[i_n][j_n] = 2
        
    return maxv
            
            
def main():        
    maxv = 0
    for i in range(row):
        for j in range(col):
            maxv = max(maxv, BPS(i,j))
    print(maxv)
                    
                
                    
    
main()

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(si, sj):
    q = deque()
    q.append([si, sj, 0])
    used = set([])
    ans = MAX_VALUE
    while len(q) > 0:
        prvi, prvj, d = q.popleft()
        for i, j in [[prvi-1, prvj], [prvi+1, prvj], [prvi, prvj-1], [prvi, prvj+1]]:
            if grid[j][i] == '#' or (i,j) in used:
                ans = min(ans, d)
                continue
            else:
                q.append([i,j,d+1])
                used.add((i,j))
    return d

H, W = map(int, input().split())
MAX_VALUE = H * W + 1
grid = ['#'*(W+2)] + [ '#' + input() + '#' for _ in range(H)] + ['#'*(W+2)]

ans = 0
for j in range(1, H + 1):
    for i in range(1, W + 1):
        if grid[j][i] == '#':
            continue
        res = bfs(i,j)
        if res != MAX_VALUE:
            ans = max(ans, res)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[] for _ in range(num)]
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

H,W = II()
S = [list(map(str, input())) for _ in range(H)]

def bfs(c,s):
    X=[[-1]*W for i in range(H)]
    X[s[0]][s[1]]=0
    q=[s]
    counter=1
    d = [(0,1),(0,-1),(1,0),(-1,0)]
    #f = float('inf')
    while q:
        q1=[]
        for i in q:
            for d0 in d:
                j = (i[0]+d0[0],i[1]+d0[1])
                if 0<=j[0]<=H-1 and 0<=j[1]<=W-1:
                    if c[j[0]][j[1]]=='.':
                        #if j[0]==g[0] and j[1]==g[1]:
                        #    f = min(f,counter)
                        if X[j[0]][j[1]]==-1:
                            X[j[0]][j[1]]=counter
                            q1.append(j)
        q=q1
        counter+=1
    return X

ans = 0
for si in range(H):
    for sj in range(W):
        d = bfs(S,(si,sj))
        #print(d)
        now = 0
        for i in range(len(d)):
            for j in range(len(d[0])):
                if d[i][j]>now:
                    now = d[i][j]
        if now==-1:
            continue
        if now>ans:
            ans = now
print(ans)

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
s=[list(input())for i in range(h)]
d=0
for i in range(h):
    if d:
        break
    for j in range(w):
        if s[i][j]==".":
            p=[i,j]
            d=1
            break
q=[p]
t=[[1]*w for j in range(h)]
t[p[0]][p[1]]=1
while q:
    c=[]
    for i,j in q:
        a=[1,-1,0,0]
        b=[0,0,1,-1]
        for d in range(4):
            if 0<=i+a[d]<h and 0<=j+b[d]<w:
                if s[i+a[d]][j+b[d]]==".":
                    if t[i+a[d]][j+b[d]]:
                        t[i+a[d]][j+b[d]]=0
                        c.append([i+a[d],j+b[d]])
    if len(c)==0:
        p=[q[0][0],q[0][1]]
        break
    else:
        q=c[::]
q=[p]
t=[[1]*w for j in range(h)]
t[p[0]][p[1]]=0
g=0
while q:
    c=[]
    for i,j in q:
        a=[1,-1,0,0]
        b=[0,0,1,-1]
        for d in range(4):
            if 0<=i+a[d]<h and 0<=j+b[d]<w:
                if s[i+a[d]][j+b[d]]==".":
                    if t[i+a[d]][j+b[d]]:
                        t[i+a[d]][j+b[d]]=0
                        c.append([i+a[d],j+b[d]])
    if len(c)==0:
        break
    else:
        g+=1
        q=c[::]
print(g)

Submission status: Wrong Answer

Solution code:
#幅優先探索


from queue import Queue

ans = 0
h,w = map(int, input().split())
maps = [input() for _ in range(h)]
for i in range(h):
  for j in range(w):
    visited = [[-1]*w for _ in range(h)]
    q = Queue()
    q.put([i,j])
    visited[i][j] = 0
    while not q.empty():
      y,x = q.get()
      for k,l in [[1,0],[-1,0],[0,1],[0,-1]]:
        if 0 <= y+k < h and 0<= x+l < w:
            new_y,new_x = y+k,x+l
        else: continue
        if visited[new_y][new_x]== -1 and maps[new_y][new_x]==".":
          visited[new_y][new_x]=visited[y][x]+1
          q.put([new_y,new_x])
         
    for ii in range(h):
      for jj in range(w):
        ans = max(ans,visited[ii][jj])
        
print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
grid=[None]*H
# 仮のスタート
sx,sy=-1,-1
found=False
for i in range(H):
  grid[i]=input()
  if not found:
    for j in range(len(grid[i])):
      if grid[i][j]==".":
        sy=i
        sx=j
        found=True
        
from collections import deque
stack=deque()
# y,x,そこまでの距離
stack.append([sy,sx,0])
INF=10**9
seen=[[INF for j in range(W)] for i in range(H)]

longest=0
longestY=-1
longestX=-1
while stack:
  node=stack.popleft()
  y=node[0]
  x=node[1]
  dist=node[2]
  if grid[y][x]=="#":
    continue
  if seen[y][x]<=dist:
    continue
  if dist>longest:
    longest=dist
    longestY=y
    longestX=x
  seen[y][x]=dist
  if y-1>=0:
    stack.append([y-1,x,dist+1])
  if y+1<H:
    stack.append([y+1,x,dist+1])
  if x-1>=0:
    stack.append([y,x-1,dist+1])
  if x+1<W:
    stack.append([y,x+1,dist+1])
    
stack=deque()
stack.append([longestY,longestX,0])
seen=[[INF for j in range(W)] for i in range(H)]
longest=0
while stack:
  node=stack.popleft()
  y=node[0]
  x=node[1]
  dist=node[2]
  if grid[y][x]=="#":
    continue
  if seen[y][x]<=dist:
    continue
  if dist>longest:
    longest=dist
  seen[y][x]=dist
  if y-1>=0:
    stack.append([y-1,x,dist+1])
  if y+1<H:
    stack.append([y+1,x,dist+1])
  if x-1>=0:
    stack.append([y,x-1,dist+1])
  if x+1<W:
    stack.append([y,x+1,dist+1])

print(longest)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
from collections import deque

h, w = [int(item) for item in input().split()]
field = []
field.append("#" * (w + 2))
for i in range(h):
    field.append("#" + input().rstrip() + "#")
field.append("#" * (w + 2))


ans = 0
for i in range(1, h+1):
    for j in range(1, w+1):
        dist = [[-1] * (w + 2) for _ in range(h + 2)]
        dist[i][j] = 0
        dq = deque()
        dq.append((i, j, 0))
        while dq:
            x, y, d = dq.popleft()
            if field[x+1][y] == "." and dist[x+1][y] == -1:
                dist[x+1][y] = d+1
                dq.append((x+1, y, d+1))
            if field[x][y+1] == "." and dist[x][y+1] == -1:
                dist[x][y+1] = d+1
                dq.append((x, y+1, d+1))
            if field[x-1][y] == "." and dist[x-1][y] == -1:
                dist[x-1][y] = d+1
                dq.append((x-1, y, d+1))
            if field[x][y-1] == "." and dist[x][y-1] == -1:
                dist[x][y-1] = d+1
                dq.append((x, y-1, d+1))
        for line in dist:
            ans = max(ans, max(line))
        
print(ans)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
visited = [[0 for _ in range(w)] for _ in range(h)]
# print(s)
for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            visited[i][j] = 1
import copy

ans = 0
for iS in range(h):
    for jS in range(w):
        for iG in range(h):
            for jG in range(w):
                if s[iS][jS] == "#" or iS == iG or jS == jG:
                    continue
                thisVisited = copy.deepcopy(visited)
                now = 0
                dis = 0
                next_point = [[iS, jS, dis]]
                thisVisited[iS][jS] = 1
                while now < len(next_point):
                    nowi = next_point[now][0]
                    nowj = next_point[now][1]
                    nowdis = next_point[now][2]
                    # print(nowi, nowj, iG, jG, nowdis)

                    if nowi == iG and nowj == jG:
                        ans = max(nowdis, ans)
                        break

                    if nowi != 0:
                        if thisVisited[nowi - 1][nowj] == 0:
                            next_point.append([nowi - 1, nowj, nowdis + 1])
                            thisVisited[nowi - 1][nowj] = 1

                    if nowi != h - 1:
                        if thisVisited[nowi + 1][nowj] == 0:
                            next_point.append([nowi + 1, nowj, nowdis + 1])
                            thisVisited[nowi + 1][nowj] = 1

                    if nowj != w - 1:
                        if thisVisited[nowi][nowj + 1] == 0:
                            next_point.append([nowi, nowj + 1, nowdis + 1])
                            thisVisited[nowi][nowj + 1] = 1

                    if nowj != 0:
                        if thisVisited[nowi][nowj - 1] == 0:
                            next_point.append([nowi, nowj - 1, nowdis + 1])
                            thisVisited[nowi][nowj - 1] = 1

                    now += 1
                # print(next_point)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[] for _ in range(num)]
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

H,W = II()
S = [list(map(str, input())) for _ in range(H)]

def bfs(c,s):
    X=[[-1]*W for i in range(H)]
    X[s[0]][s[1]]=0
    q=[s]
    counter=1
    d = [(0,1),(0,-1),(1,0),(-1,0)]
    #f = float('inf')
    while q:
        q1=[]
        for i in q:
            for d0 in d:
                j = (i[0]+d0[0],i[1]+d0[1])
                if 0<=j[0]<=H-1 and 0<=j[1]<=W-1:
                    if c[j[0]][j[1]]=='.':
                        #if j[0]==g[0] and j[1]==g[1]:
                        #    f = min(f,counter)
                        if X[j[0]][j[1]]==-1:
                            X[j[0]][j[1]]=counter
                            q1.append(j)
        q=q1
        counter+=1
    return X

ans = 0
for si in range(H):
    for sj in range(W):
        d = bfs(S,(si,sj))
        #print(d)
        now = 0
        for i in range(len(d)):
            for j in range(len(d[0])):
                if d[i][j]>now:
                    now = d[i][j]
        if now>ans:
            ans = now
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
 
 
def main():
    H, W = [int(x) for x in input().split()]
    A = [["" for i in range(W)] for j in range(H)]
 
    for j in range(H):
        S = input().strip()
        for i, s in enumerate(list(S)):
            A[j][i] = s
 
 
    ma = 0
 
    dj = [1, 0, -1, 0]
    di = [0, 1, 0, -1]
 
    for sj in range(H):
        for si in range(W):
            for gj in range(H):
                for gi in range(W):
                    d = [[-1] * W for i in range(H)]
                    q = deque([])
                    q.append((sj, si))
                    d[sj][si] = 0
 
                    while q:
                        p = q.popleft()
                        if p[0] == gj and p[1] == gi:
                            break
                        for i in range(4):
                            nj = p[0] + dj[i]
                            ni = p[1] + di[i]
 
                            if 0 <= nj < H and 0 <= ni < W and A[nj][ni] != "#" and d[nj][ni] == -1:
                                q.append((nj, ni))
                                d[nj][ni] = d[p[0]][p[1]] + 1
 
                    ma = max(ma, d[gj][gi])
 
 
 
    print(ma)
 
 
 
 
 
    
 
 
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# A happy new year, AtCoder !
H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]

myinf = 10 ** 9 + 7
tab_graph = [[myinf] * (H * W) for _ in range(H * W)]

for i in range(H):
    for j in range(W):
        for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            if i + di < 0: continue
            if i + di >= H: continue
            if j + dj < 0: continue
            if j + dj >= W: continue
            # print("#", i, j, '->', i + di, j + dj)
            if S[i + di][j + dj] == '#': continue
            #
            src = i * W + j
            dst = (i + di) * W + (j + dj)
            tab_graph[src][dst] = 1

from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

G = csgraph_from_dense(tab_graph, null_value=myinf)
d = floyd_warshall(G)

# print("#", d)
ans = 0
for i in range(H * W):
    for j in range(H * W):
        if i == j: continue
        # print("##", i, j, d[i][j])
        if d[i][j] < myinf: ans = max(ans, int(d[i][j]))

print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
S=[[1 if c=='#' else 0 for c in input()] for i in range(H)]
from collections import deque
r=0
for i in range(H):
    for j in range(W):
        if S[i][j]==1:
            continue
        d=[[-1]*W for x in range(H)]
        q=deque([(i,j,0)])
        while q:
            x,y,d0=q.popleft()
            if x>0 and S[x-1][y]==0 and d[x-1][y]==-1:
                q.append((x-1,y,d0+1))
                d[x-1][y]=d0+1
            if y>0 and S[x][y-1]==0 and d[x][y-1]==-1:
                q.append((x,y-1,d0+1))
                d[x][y-1]=d0+1
            if x<H-1 and S[x+1][y]==0 and d[x+1][y]==-1:
                q.append((x+1,y,d0+1))
                d[x+1][y]=d0+1
            if y<W-1 and S[x][y+1]==0 and d[x][y+1]==-1:
                q.append((x,y+1,d0+1))
                d[x][y+1]=d0+1
        r=max(r,d0)
print(r)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline

H, W = map(int, readline().split())
S = tuple(read().split())


def bfs(grid, start):
    distance = [[0] * W for _ in range(H)]
    queue = deque([start])
    visited = set()
    while queue:
        x, y = queue.popleft()
        visited.add((x, y))

        for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y + j, x + i
            if 0 <= new_y < W and 0 <= new_x < H:
                if grid[new_x][new_y] == '.' and (new_x, new_y) not in visited:
                    distance[new_x][new_y] = distance[x][y] + 1
                    queue.append((new_x, new_y))
    return distance


answer = 0
for i in range(H):
    for j in range(W):
        tmp = max(map(max, bfs(S, (i, j))))
        if tmp > answer:
            answer=tmp

print(answer)

Submission status: Wrong Answer

Solution code:
def main():
    from collections import deque

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

    s = [input() for _ in range(h)]

    drdc = (1, 0), (-1, 0), (0, 1), (0, -1)

    dist = [[-1] * w for _ in range(h)]

    vs = []
    for r in range(h):
        for c in range(w):
            if dist[r][c] == -1 and s[r][c] == '.':
                dist[r][c] = 0

                q = deque()
                q.append((r, c, 0))

                while q:
                    qr, qc, d = q.popleft()
                    for dr, dc in drdc:
                        nr = qr + dr
                        if nr < 0 or h <= nr:
                            continue
                        nc = qc + dc
                        if nc < 0 or w <= nc:
                            continue
                        if s[nr][nc] == '#':
                            continue
                        if dist[nr][nc] != -1:
                            continue
                        dist[nr][nc] = d + 1
                        q.append((nr, nc, d + 1))

                vs.append((qr, qc))

    dist = [[-1] * w for _ in range(h)]

    max_d = -1

    for sr, sc in vs:
        q = deque()
        q.append((sr, sc, 0))
        dist[sr][sc] = 0

        while q:
            r, c, d = q.popleft()
            for dr, dc in drdc:
                nr = r + dr
                if nr < 0 or h <= nr:
                    continue
                nc = c + dc
                if nc < 0 or w <= nc:
                    continue
                if s[nr][nc] == '#':
                    continue
                if dist[nr][nc] != -1:
                    continue
                dist[nr][nc] = d + 1
                q.append((nr, nc, d + 1))

        max_d = max(max_d, d)

    print(max_d)


if __name__ == '__main__':
    main()

# import sys
#
# sys.setrecursionlimit(10 ** 7)
#
# input = sys.stdin.readline
# rstrip()

# int(input())
# map(int, input().split())

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())

n_list = []
v_table = {}
for y in range(H):
	for x in range(W):
		n = (x, y)
		n_list.append(n)
		v_table[n] = []

prev = None
ns = None
for y in range(H):
	cur = input()
	for x in range(W):
		if cur[x] == ".":
			nc = (x, y)
			ns = nc
			if y > 0 and prev[x] == ".":
				np = (x, (y - 1))
				v_table[np].append(nc)
				v_table[nc].append(np)
			if x > 0 and cur[x - 1] == ".":
				np = (x - 1, y)
				v_table[np].append(nc)
				v_table[nc].append(np)
	prev = cur

def find_farthest(x, n_list, edges):
	dists = { x: 0 }
	queue = [ x ]
	
	while queue:
		cur = queue.pop()
		dist = dists[cur] + 1
		for v2 in edges[cur]:
			if (not v2 in dists) or (dists[v2] > dist):
				dists[v2] = dist
				queue.append(v2)
	farthest = (x, 0)
	for n in n_list:
		if n in dists and farthest[1] < dists[n]:
			farthest = (n, dists[n])
	
	return farthest

f1 = find_farthest(ns, n_list, v_table)
f2 = find_farthest(f1[0], n_list, v_table)
print(f2[1])

Submission status: Wrong Answer

Solution code:
def meiro(sx,sy,gx,gy):
    num = [[-1] * w for i in range(h)]
    num[sx][sy] = 0
    now = {(sx,sy)}
    for i in range(1,40):
        tmp = set()
        for x,y in now:
            if x > 0:
                if lis[x-1][y] == "." and num[x-1][y] == -1:
                    num[x-1][y] = i
                    tmp.add((x-1,y))
            if x < h-1:
                if lis[x+1][y] == "." and num[x+1][y] == -1:
                    num[x+1][y] = i
                    tmp.add((x+1,y))
            if y > 0:
                if lis[x][y-1] == "." and num[x][y-1] == -1:
                    num[x][y-1] = i
                    tmp.add((x,y-1))
            if y < w-1:
                if lis[x][y+1] == "." and num[x][y+1] == -1:
                    num[x][y+1] = i
                    tmp.add((x,y+1))
        now = tmp
    return num[gx][gy]

h,w = map(int,input().split())
lis = [str(input()) for i in range(h)]
ans = 0
for sx in range(h):
    for sy in range(w):
      for gx in range(h):
          for gy in range(w):
              ans = max(ans,meiro(sx,sy,gx,gy))
              print(meiro(sx,sy,gx,gy))
print(ans)

Submission status: Wrong Answer

Solution code:
from queue import Queue
from copy import deepcopy

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

WHITE = 0
GRAY = 1
BLACK = 2

dhw = [[-1, 0], [1, 0], [0, -1], [0, 1]]

color_orginal = [[WHITE] * w for _ in range(h)]
for hi in range(h):
    for wi in range(w):
        if s[hi][wi] == "#":
            color_orginal[hi][wi] = BLACK


def dfs(sh, sw):
    q = Queue()
    q.put([sh, sw])

    color = deepcopy(color_orginal)
    d = [[-1] * w for _ in range(h)]

    d[sh][sw] = 0
    dd = 0

    while not q.empty():
        uh, uw = q.get()
        color[uh][uw] = BLACK
        for dh, dw in dhw:
            nxth = uh + dh
            nxtw = uw + dw
            if 0 <= nxth <= h - 1 and 0 <= nxtw <= w - 1:
                if color[nxth][nxtw] == WHITE:
                    q.put([nxth, nxtw])
                    color[nxth][nxtw] = GRAY
                    d[nxth][nxtw] = d[uh][uw] + 1
                    dd = max(d[nxth][nxtw], dd)

    return dd


ans = 0
for hi in range(h):
    for wi in range(w):
        ans = max(ans, dfs(hi, wi))

print(ans)

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())

a= []

for i in range(h):
    arrc = input()
    a.append(arrc)
ans = 0
for gg in range(1,h+1):
    for bb in range(1,w+1):
        ys=gg
        xs=bb
        n=[(ys-1,xs-1)]
        route={n[0]:0}
        p=[[1,0],[0,1],[-1,0],[0,-1]]
        count=1
        while count != 401:
            n2=[]
            for i in n:
                for j in p:
                   
                    np=(i[0]+j[0],i[1]+j[1])
                    if 0<=np[0]<=h-1 and 0<=np[1]<=w-1:
                        if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                            n2.append(np)
                            route[np]=count
            n=n2
            count+=1
        
        ll= max(list(route.values()))
        if ll > ans:
            ans = ll

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

H,W=map(int,input().split())
S=[list(input().strip()) for _ in range(H)]
G=[[float("inf")]*H*W for _ in range(H*W)]
#print(S)
for h in range(H):
    for w in range(W-1):
        if S[h][w]=="." and S[h][w+1]==".":
            G[W*h+w][W*h+w+1]=1
            G[W*h+w+1][W*h+w]=1

for h in range(H-1):
    for w in range(W):
        if S[h][w]=="." and S[h+1][w]==".":
            G[W*h+w][W*(h+1)+w]=1
            G[W*(h+1)+w][W*h+w]=1

#print(G)
n=H*W
G=warshall_floyd(G)
#print(G)
ans=0
for h in range(H*W):
    for w in range(H*W):
        if G[h][w]!=float("inf"):
            ans=max(ans,G[h][w])
print(ans)

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
S = [input() for _ in range(H)]
        
from collections import deque

ans = 0
inf = 10**12
for i in range(H):
    for j in range(i, W):
        if S[i][j] == "#":
            continue
        q = deque()
        q.append((i, j, 0))
        used = [[inf]*W for _ in range(H)]
        used[i][j] = 0
        while q:
            temp = q.popleft()
            k = temp[0]
            l = temp[1]
            d = temp[2]
            if k > 0 and S[k-1][l] == "." and used[k-1][l] > d+1:
                used[k-1][l] = d+1
                q.append((k-1, l, d+1))
            if k < H-1 and S[k+1][l] == "." and used[k+1][l] > d+1:
                used[k+1][l] = d+1
                q.append((k+1, l, d+1))
            if l > 0 and S[k][l-1] == "." and used[k][l-1] > d+1:
                used[k][l-1] = d+1
                q.append((k, l-1, d+1))
            if l < W-1 and S[k][l+1] == "." and used[k][l+1] > d+1:
                used[k][l+1] = d+1
                q.append((k, l+1, d+1))

        for s in range(H):
            for t in range(W):
                if used[s][t] < inf:
                    ans = max(ans, used[s][t])

print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
inf=float("inf")
data=[[inf]*W for i in range(H)]
d=[[1,0],[0,1],[-1,0],[0,-1]]
que=[[0,0]]
data[0][0]=0
count=1
while que:
    h=[]
    for x,y in que:
        for dx,dy in d:
            nx,ny=x+dx,y+dy
            if 0<=nx<H and 0<=ny<W and S[nx][ny]=="." and data[nx][ny]==inf:
                h.append([nx,ny])
                data[nx][ny]=count
    que=h
    count+=1
z=[0,0]
num=0
for i in range(H):
    for j in range(W):
        if data[i][j]!=inf and data[i][j]>num:
            num=data[i][j]
            z=[i,j]

data=[[inf]*W for i in range(H)]
que=[z]
data[z[0]][z[1]]=0
count=1
while que:
    h=[]
    for x,y in que:
        for dx,dy in d:
            nx,ny=x+dx,y+dy
            if 0<=nx<H and 0<=ny<W and S[nx][ny]=="." and data[nx][ny]==inf:
                h.append([nx,ny])
                data[nx][ny]=count
    que=h
    count+=1
ans=0
for i in range(H):
    for j in range(W):
        if data[i][j]==inf:
            continue
        ans=max(ans,data[i][j])
print(ans)