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 copy
from collections import deque

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


def check(tup):
    global H
    global W
    global S

    tup_x=tup[0]
    tup_y=tup[1]
    if 0<=tup_x<H and 0<=tup_y<W:
        if S[tup_x][tup_y]=='.':
            return True
    else:
        return False

def neighbor(tup):
    x=tup[0]
    y=tup[1]
    cand=[(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
    List=[]
    for c in cand:
        if check(c):
            List.append(c)
    return List

def bfs(start):#startはtuple型
    global H
    global W

    deq=deque()#as queue
    Dict=[]
    component=[]
    for i in range(W):
        component.append(-1)
    for j in range(H):
        Dict.append(copy.copy(component))

    deq.append(start)
    Dict[start[0]][start[1]]=0
    while deq:
        now=deq.popleft()
        nexts=neighbor(now)
        for next in nexts:
            next_x=next[0]
            next_y=next[1]
            if Dict[next_x][next_y]>=0:
                continue
            if next in deq:
                continue
            deq.append(next)
            Dict[next_x][next_y]=Dict[now[0]][now[1]]+1

    M=[]
    for d in Dict:
        M.append(max(d))
    return max(M)

Ans=[]
for k in range(H):
    for l in range(W):
        Ans.append(bfs((k,l)))

print(max(Ans))

Submission status: Wrong Answer

Solution code:
from collections import deque
import pprint
import numpy as np

h, w = map(int, input().split())
maze = [['*']*(w+2) for j in range(h+2)]
for i in range(1,h+1):
    maze[i][1:] = map(str,list(input()))
    maze[i].append('*')

score = []
def bfs(maze):
    for i in range(1,h+1):
        for l in range(1,w+1):
            if i == '#' or l == '#':
                continue
            visited = [[-1]*(w+1) for j in range(h+1)]
            queue = deque()
            queue.append([i, l])
            visited[i][l] = 0
            while(queue):
                y, x = queue.popleft()
                for j,k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
                    new_x, new_y = x+j, y+k
                    if maze[new_y][new_x] == '.' and visited[new_y][new_x] == -1:
                        queue.append([new_y, new_x])
                        visited[new_y][new_x] = visited[y][x] + 1
            idx = np.unravel_index(np.argmax(np.array(visited)), np.array(visited).shape)
            score.append(np.array(visited)[idx])
    return (max(score))

print(bfs(maze))

Submission status: Wrong Answer

Solution code:
from collections import deque
import pprint
import numpy as np

h, w = map(int, input().split())
maze = [['*']*(w+2) for j in range(h+2)]
for i in range(1,h+1):
    maze[i][1:] = map(str,list(input()))
    maze[i].append('*')

score = []
def bfs(maze):
    for i in range(1,h+1):
        for l in range(1,w+1):
            visited = [[-1]*(w+1) for j in range(h+1)]
            queue = deque()
            queue.append([i, l])
            visited[i][l] = 0
            while(queue):
                y, x = queue.popleft()
                for j,k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
                    new_x, new_y = x+j, y+k
                    if maze[new_y][new_x] == '.' and visited[new_y][new_x] == -1:
                        queue.append([new_y, new_x])
                        visited[new_y][new_x] = visited[y][x] + 1
            idx = np.unravel_index(np.argmax(np.array(visited)), np.array(visited).shape)
            score.append(np.array(visited)[idx])
    return (max(score))

print(bfs(maze))

Submission status: Wrong Answer

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

dxy = [[-1, 0], [0, 1], [1, 0], [0, -1]]

ans = 0
for h in range(H):
  for w in range(W):
    if maze[h][w] == '#':
      continue
    d_maze = [[-1]*W for _ in range(H)]
    d_maze[h][w] = 0
    p = [[h, w]]
    p = deque(p)
    while p:
      rh, rw =  p.popleft()
      for i, j in dxy:
        nh = rh + i
        nw = rw + j
        if 0 <= nh < H and 0 <= nw < W and maze[nh][nw] == '.' and d_maze[nh][nw] == -1:
          d_maze[nh][nw] = d_maze[rh][rw] + 1
          p.append([nh, nw])
    ans = max(ans, max(max([l for l in d_maze])))
print(ans)

Submission status: Wrong Answer

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

dxy = [[-1, 0], [0, 1], [1, 0], [0, -1]]

ans = 0
for h in range(H):
  for w in range(W):
    if maze[h][w] == '#':
      continue
    d_maze = [[-1]*W for _ in range(H)]
    d_maze[h][w] = 0
    p = [[h, w]]
    p = deque(p)
    while p:
      rh, rw =  p.popleft()
      for i, j in dxy:
        if rh + i < 0 or rh + i >= H:
          continue
        if rw + j < 0 or rw + j >= W:
          continue
        if d_maze[rh + i][rw + j] == -1 and not maze[rh + i][rw + j] == '#':
          d_maze[rh + i][rw + j] = d_maze[rh][rw] + 1
          p.append([rh + i, rw + j])
    ans = max(ans, max(max([l for l in d_maze])))
print(ans)

Submission status: Wrong Answer

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

dxy = [[-1, 0], [0, 1], [1, 0], [0, -1]]

ans = 0
for h in range(H):
  for w in range(W):
    if maze[h][w] == '#':
      continue
    d_maze = [[-1]*W for _ in range(H)]
    d_maze[h][w] = 0
    p = [[h, w]]
    p = deque(p)
    while p:
      rh, rw =  p.popleft()
      for i, j in dxy:
        if rh + i < 0 or rh + i >= H:
          continue
        if rw + j < 0 or rw + j >= W:
          continue
        if maze[rh + i][rw + j] == '#':
          continue
        if d_maze[rh + i][rw + j] == -1:
          d_maze[rh + i][rw + j] = d_maze[rh][rw] + 1
          p.append([rh + i, rw + j])
    ans = max(ans, max(max([l for l in d_maze])))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque


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

def bfs(sx,sy,gx,gy):
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    d = [[float('inf')]*w for i in range(h)]
    q = deque()
    q.append((sx,sy))
    d[sx][sy] = 0
    while q:
        x,y = q.popleft()
        if x == gx and y == gy:
            break
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if  0<= nx < h and 0 <= ny < w and d[nx][ny]==float('inf') and s[nx][ny]=='.':
                q.append((nx,ny))
                d[nx][ny] = d[x][y]+1
    return d[gx][gy]

count = 0
for i in range(h):
    for j in range(w):
        for k in range(i,h):
            for l in range(j,w):
                if s[i][j] != '#' and s[k][l] != '#':
                    count  = max(count, bfs(i,j,k,l))
print(count)

Submission status: Wrong Answer

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

from copy import deepcopy
import itertools

h,w=n1()
s=s2(h)
s=["#"+x+"#" for x in s]
s=["#"*(w+2)]+s+["#"*(w+2)]
meiro_original=[[0]*(w+2) for _ in range(h+2)]
road=[]
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j]=="#":
            meiro_original[i][j]=2
        else:
            meiro_original[i][j]=0
            road.append([i,j])

def calc(start):
    ans=0
    meiro=deepcopy(meiro_original)
    pos=[[start[0],start[1],0]]
    while len(pos)>0:
        x,y,c=pos.pop(0)

        meiro[x][y]=2

        f=False
        if meiro[x-1][y]<2:
            pos.append([x-1,y,c+1])
            f=True
        if meiro[x+1][y]<2:
            pos.append([x+1,y,c+1])
            f=True
        if meiro[x][y-1]<2:
            pos.append([x,y-1,c+1]) 
            f=True
        if meiro[x][y+1]<2:
            pos.append([x,y+1,c+1])
            f=True
        if f==False:
            ans=max(ans,c)   
    return ans

l=0
for line in road:
    x,y=line
    if meiro_original[x-1][y]==meiro_original[x+1][y]==0 or meiro_original[x][y-1]==meiro_original[x][y+1]==0:
        pass
    else:
        l=max(l,calc(line))
    
print(l)

Submission status: Wrong Answer

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

from copy import deepcopy
import itertools

h,w=n1()
s=s2(h)
s=["#"+x+"#" for x in s]
s=["#"*(w+2)]+s+["#"*(w+2)]
meiro_original=[[0]*(w+2) for _ in range(h+2)]
road=[]
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j]=="#":
            meiro_original[i][j]=2
        else:
            meiro_original[i][j]=0
            road.append([i,j])

def calc(start):
    ans=0
    meiro=deepcopy(meiro_original)
    pos=[[start[0],start[1],0]]
    while len(pos)>0:
        x,y,c=pos.pop()

        meiro[x][y]=2

        f=False
        if meiro[x-1][y]<2:
            pos.append([x-1,y,c+1])
            f=True
        if meiro[x+1][y]<2:
            pos.append([x+1,y,c+1])
            f=True
        if meiro[x][y-1]<2:
            pos.append([x,y-1,c+1]) 
            f=True
        if meiro[x][y+1]<2:
            pos.append([x,y+1,c+1])
            f=True
        if f==False:
            ans=max(ans,c)   
    return ans

l=0
for x in road:
    l=max(l,calc(x))
    
print(l)

Submission status: Wrong Answer

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

from copy import deepcopy
import itertools

h,w=n1()
s=s2(h)
s=["#"+x+"#" for x in s]
s=["#"*(w+2)]+s+["#"*(w+2)]
meiro_original=[[0]*(w+2) for _ in range(h+2)]
road=[]
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j]=="#":
            meiro_original[i][j]=2
        else:
            meiro_original[i][j]=0
            road.append([i,j])

def calc(start,goal):
    min_count=9999999999
    meiro=deepcopy(meiro_original)
    meiro[goal[0]][goal[1]]=1
    pos=[[start[0],start[1],0]]
    while len(pos)>0:
        x,y,count=pos.pop(0)

        if meiro[x][y]==1:
            min_count=min(count,min_count)
            break

        meiro[x][y]=2

        if meiro[x-1][y]<2:
            pos.append([x-1,y,count+1])    
        if meiro[x+1][y]<2:
            pos.append([x+1,y,count+1])    
        if meiro[x][y-1]<2:
            pos.append([x,y-1,count+1]) 
        if meiro[x][y+1]<2:
            pos.append([x,y+1,count+1])

    return min_count

def check(line):
    global meiro_original
    x,y=line
    return meiro_original[x-1][y]==meiro_original[x+1][y]==0 or meiro_original[x][y-1]==meiro_original[x][y+1]==0

ans=0
for x in itertools.combinations(road,2):
    if check(x[0]) or check(x[1]):
        pass
    else:
        ans=max(ans,calc(x[0],x[1]))
    
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(start, maze, H, W):
    max_step = 0
    used = [[False for _ in range(W)] for _ in range(H)]
    start_x, start_y = start
    used[start_x][start_y] = True
    stack = deque([[start, 0]])
    while stack:
        (i, j), step = stack.popleft()
        if maze[i][j] == '#':
            continue
        max_step = max(max_step, step)
        for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            if 0 <= x < H and 0 <= y < W and not used[x][y]:
                stack.append([(x, y), step + 1])
                used[x][y] = True
    return max_step

if __name__ == '__main__':
    H, W = map(int, input().split())
    S = []
    for _ in range(H):
        S.append(list(input()))
    ret = 0
    for i in range(H):
        for j in range(W):
            ret = max(ret, bfs((i, j), S, H, W))
            break
        break
    print(ret)

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(start, maze, H, W):
    max_step = 0
    used = [[False for _ in range(W)] for _ in range(H)]
    completed = []
    stack = deque([[start, 0]])
    while stack:
        (i, j), step = stack.popleft()
        used[i][j] = True
        if maze[i][j] == '#':
            continue
        max_step = max(max_step, step)
        is_proceeding = False
        for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            if 0 <= x < H and 0 <= y < W and not used[x][y]:
                stack.append([(x, y), step + 1])
                is_proceeding = True
        if is_proceeding:
            completed.append([i, j])
    return max_step, completed

if __name__ == '__main__':
    H, W = map(int, input().split())
    S = []
    for _ in range(H):
        S.append(list(input()))
    ret = 0
    used = [[False for _ in range(W)] for _ in range(H)]
    for i in range(H):
        for j in range(W):
            if used[i][j]:
                continue
            step, completed = bfs((i, j), S, H, W)
            ret = max(ret, step)
            for x, y in completed:
                used[x][y] = True
    print(ret)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

for h in range(H):
  for w in range(W): #スタートが(h,w)
    if S[h][w] == '#':
      continue
    d = [[-1]*W for i in range(H)]
    d[h][w] = 0
    
    q = deque([[h,w]])
    
    while q:
      nh,nw = q.pop()
      
      if nw+1<W and S[nh][nw+1]=='.' and d[nh][nw+1]==-1:
        d[nh][nw+1] = d[nh][nw]+1
        q.append([nh,nw+1])
      if 0<=nw-1 and S[nh][nw-1]=='.' and d[nh][nw-1]==-1:
        d[nh][nw-1] = d[nh][nw]+1
        q.append([nh,nw-1])
      if nh+1<H and S[nh+1][nw]=='.' and d[nh+1][nw]==-1:
        d[nh+1][nw] = d[nh][nw]+1
        q.append([nh+1,nw])
      if 0<=nh-1 and S[nh-1][nw]=='.' and d[nh-1][nw]==-1:
        d[nh-1][nw] = d[nh][nw]+1
        q.append([nh-1,nw])
    a = max(a,max([max(i) for i in d]))
    
print(a)

Submission status: Wrong Answer

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

q = Queue()
searched = [[False for _ in range(W)] for __ in range(H)]
dist = [[-1 for _ in range(W)] for __ in range(H)]

def bfs(x, y, d):
    if not (0 <= x < W and 0 <= y < H):
        return
    if S[y][x] == '#':
        return
    if searched[y][x]:
        return
    searched[y][x] = True
    dist[y][x] = d
    q.put([x, y, d])
    return

ans = 0
for s_y in range(H):
    for s_x in range(W):
        q = Queue()
        searched = [[False for _ in range(W)] for __ in range(H)]
        dist = [[-1 for _ in range(W)] for __ in range(H)]
        
        dist[s_y][s_x] = 0
        searched[s_y][s_x] = True
        
        q.put([s_x, s_y, 0])
        
        while not q.empty():
            x, y, d = q.get()
            bfs(x-1, y, d+1)
            bfs(x+1, y, d+1)
            bfs(x, y-1, d+1)
            bfs(x, y+1, d+1)
        
        dist_max = max(list(map(lambda x: max(x), dist)))
        ans = max(ans, dist_max)

print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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


def check(tup):
    tup_x=tup[0]
    tup_y=tup[1]
    if 0<=tup_x<H and 0<=tup_y<W:
        if S[tup_x][tup_y]=='.':
            return True
    else:
        return False

def neighbor(tup):
    x=tup[0]
    y=tup[1]
    cand=[(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
    List=[]
    for a in range(4):
        if check(cand[a]):
            List.append(cand[a])
    return List

def bfs(start):#startはtuple型
    deq=deque()
    Dict=[]
    component=[]
    for i in range(W):
        component.append(-1)
    for j in range(H):
        Dict.append(copy.copy(component))

    deq.append(start)
    Dict[start[0]][start[1]]=0
    while len(deq)>0:
        now=deq.popleft()
        nexts_list=neighbor(now)
        for a in range(len(nexts_list)):
            next=nexts_list[a]
            next_x=next[0]
            next_y=next[1]
            if Dict[next_x][next_y]>=0:
                continue
            if next in deq:
                continue
            deq.append(next)
            Dict[next_x][next_y]=Dict[now[0]][now[1]]+1

    M=[]
    for b in range(len(Dict)):
        M.append(max(Dict[b]))

    return(max(M))

Ans=[]
for k in range(H):
    for l in range(W):
        Ans.append(bfs((k,l)))

print(max(Ans))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

S = [['#'] * (W + 2)]
for _ in range(H):
    tmp = ['#'] + list(input()) + ['#']
    S.append(tmp)
S.append(['#'] * (W + 2))

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

ans = 0
for X in range(1, H + 1):
    for Y in range(1, W + 1):
        check = [[-1] * (W + 2) for _ in range(H + 2)]
        check[X][Y] = 0
        que = deque()
        que.append([X, Y])
        while que:
            tmp = que.popleft()
            x = tmp[0]
            y = tmp[1]
            flag = True
            for dx, dy in move:
                nx = x + dx
                ny = y + dy
                if S[nx][ny] == '.' and check[nx][ny] == -1:
                    que.append([nx, ny])
                    check[nx][ny] = check[x][y] + 1
                    flag = False
            if flag:
                ans = max(ans, check[x][y])


print (ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int, input().split())
Maze = [["#"]*(W+2)]+[["#"]+list(input())+["#"] for _ in range(H)] + [["#"]*(W+2)]
Ans = 0
sy = 1
while sy <= H:
  sx = 1
  while sx <= W:
    if Maze[sy][sx] == ".":
        memo = [[False]*(W+2) for _ in range(H+2)]
        q = deque()
        q.append([[sy,sx],0])
        ans = 0
        while q:
          cur, cnt = q.popleft()
          Ans = max(ans, cnt)
          memo[cur[0]][cur[1]] = True
          for y, x in zip((0,0,1,-1),(1,-1,0,0)):
            if Maze[cur[0]+y][cur[1]+x] == "." and not memo[cur[0]+y][cur[1]+x]:
              q.append([[cur[0]+y,cur[1]+x],cnt+1])
    sx += 1
  sy += 1
print(Ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
H, W = map(int, input().split())
mp = np.array([list(input()) for _ in range(H)], dtype=str)

import queue
q = queue.Queue()
visit = (mp == "#")

def can_visit(x, y):
    """訪問可能ならTrue。壁、既訪問、世界外ならFalse"""
    if x < 0 or y < 0 or x >= W or y >= H:
        return False
    return not visit[y, x]

def push_neighbor(x, y, d):
    """隣接マスをキューにpush"""
    lis = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
    for nx, ny in lis:
        if can_visit(nx, ny):
            q.put((nx, ny, d+1))
            visit[ny, nx] = True

def furthest(sx, sy):
    """位置(sx, sy)から見て一番遠い場所までの距離"""
    # 初期化
    global visit
    visit = (mp == "#")
    # 例外処理(スタート地点が壁の中)
    if visit[sy, sx]:
        return 0
    # 計算
    q.put((sx, sy, 0))
    while not q.empty():
        x, y, d = q.get()
        push_neighbor(x, y, d)
    return d
  
dist = max([furthest(sx, sy) for sx in range(W) for sy in range(H)])
print(dist)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from copy import deepcopy

h, w = map(int, readline().split())
s = [input() for i in range(h)]
q = []
start = []
dist = [[False] * w for _ in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j] != '#':
            start.append((i, j))
        else:
            dist[i][j] = True
test = [(0, 1), (0, -1), (1, 0), (-1, 0)]
ans = []
while start:
    check = deepcopy(dist)
    q = [start.pop()]
    cnt = -1
    while q:
        cnt += 1
        qq = []
        for y, x in q:
            for dy, dx in test:
                yy, xx = y + dy, x + dx
                if xx < 0 or yy < 0 or xx > w - 1 or yy > h - 1 or check[yy][xx]:
                    continue
                else:
                    check[yy][xx] = True
                    qq.append((yy, xx))
        q = qq
    ans.append(cnt)
print(max(ans))

Submission status: Wrong Answer

Solution code:
from collections import deque
d = [(-1,0),(1,0),(0,1),(0,-1)]

def bfs(y,x,c):
    q =  deque()
    q.append((y,x,c))
    ma = 0
    while q:
        y,x,c = q.popleft()
        ma = max(ma,c)
        for dy,dx in d:
            if 0<=y+dy<h and 0<=x+dx<w:
                if area[y+dy][x+dx] =="." and visit[y+dy][x+dx] == 0:
                    q.append((y+dy,x+dx,c+1))
                    visit[y+dy][x+dx] = 1
    return ma

h,w = map(int,input().split())
area = []
for i in range(h):
    area.append(list(input()))
ans = 0
for i in range(h):
    for j in range(w):
        if area[i][j] ==".":
            visit = [[0]*w for i in range(h)]
            ans = max(ans,bfs(i,j,0))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    depth = np.zeros((H+2, W+2), dtype=np.int32)
    q = deque()
    q.append((y, x))
    #visited[y][x] = True
    max_depth = 0
    while q:
        y, x = q.popleft()
        max_depth = max(max_depth, depth[y][x])
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if not depth[ny][nx] and S[ny][nx] == '.':
                depth[ny][nx] = depth[y][x] + 1
                q.append((ny, nx))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    visited = np.zeros((H+2, W+2), dtype=np.bool)
    q = deque()
    q.append((y, x, 1))
    #visited[y][x] = True
    max_depth = 1
    while q:
        y, x, d = q.popleft()
        max_depth = max(max_depth, d)
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if not visited[ny][nx] and S[ny][nx] == '.':
                visited[ny][nx] = True
                q.append((ny, nx, d+1))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    visited = np.zeros((H+2, W+2), dtype=np.bool)
    q = deque()
    q.append((y, x, 0))
    #visited[y][x] = True
    max_depth = 1
    while q:
        y, x, d = q.popleft()
        max_depth = max(max_depth, d)
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if not visited[ny][nx] and S[ny][nx] == '.':
                visited[ny][nx] = True
                q.append((ny, nx, d+1))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    visited = np.zeros((H+2, W+2), dtype=np.bool)
    q = deque()
    q.append((y, x, 0))
    #visited[y][x] = True
    max_depth = 0
    while q:
        y, x, d = q.popleft()
        max_depth = max(max_depth, d)
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if not visited[ny][nx] and S[ny][nx] == '.':
                visited[ny][nx] = True
                q.append((ny, nx, d+1))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    q = deque()
    q.append((y, x, 0))
    max_depth = 0
    while q:
        y, x, depth = q.popleft()
        S[y][x] = '#'
        max_depth = max(max_depth, depth)
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if S[ny][nx] == '.':
                q.append((ny, nx, depth+1))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                #print(y, x)
                d = bfs(y+1, x+1, H, W, S.copy())
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import product


def read():
    H, W = list(map(int, input().split()))
    S = ''
    S += ('#' * (W+2))
    for h in range(H):
        buf = input()
        S += '#' + buf + '#'
    S += ('#' * (W+2))
    return H, W, S


def bfs(yx, H, W, S):
    dirs = (1, W+2, -1, -W-2)
    visited = [0] * ((H+2) * (W+2))
    q = deque()
    q.append((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.popleft()
        visited[yx] = 1
        max_depth = max(max_depth, depth)
        if max_depth == (H - 1) + (W - 1):
            break
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and visited[nyx] == 0:
                q.append((nyx, depth+1))
    return max_depth


def solve(H, W, S):
    dist_max = 0
    for yx in range((H+2) * (W+2)):
        if S[yx] == '.':
            d = bfs(yx, H, W, S)
            dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(maze, visited, sy, sx):
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    ans=0
    while queue:
        y, x = queue.popleft()
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if maze[new_y][new_x] == "." and visited[new_y][new_x]==-1:
                visited[new_y][new_x]=visited[y][x]+1
                ans=max(ans,visited[new_y][new_x])
                queue.append([new_y,new_x])
    return ans
    
def make_wall(maze,h,w):
    maze=deque(maze)
    for i in range(h):
        maze[i]="#"+maze[i]+"#"
    maze.appendleft("#"*(w+2))
    maze.append("#"*(w+2))
    return list(maze)
    
h,w=map(int,input().split())
maze=[input() for _ in range(h)]
maze=make_wall(maze,h,w)
ans=0
for i in range(1,h+1):
    for j in range(1,w+1):
        visited=[[-1]*(w+2) for _ in range(h+2)]
        tmp=bfs(maze, visited, i, j)
        ans=max(ans,tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
work = [[[] for j in range(w)] for i in range(h)]
result = 0
for i in range(h):
    for j in range(w):
        if i<h-1 and s[i+1][j] == ".":
            work[i][j].append([i+1,j])
        if i>0 and s[i-1][j] == ".":
            work[i][j].append([i-1,j])
        if j<w-1 and s[i][j+1] == ".":
            work[i][j].append([i,j+1])
        if j>0 and s[i][j-1] == ".":
            work[i][j].append([i,j-1])
for i in range(h):
    for j in range(w):
        if s[i][j] != ".":
            continue
        stack = deque([[i, j]])
        temp = [[i, j]]
        distance = 0
        for k in range(h*w):
            x, y = stack.pop()
            flag = False
            for el in work[x][y]:
                if el not in temp:
                    flag = True
                    stack.append(el)
                    temp.append(el)
            if flag:
                distance += 1
            else:
                result = result if result > distance else distance
                distance = -1
            if len(stack) == 0:
                break
print(result)