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())
maze = [["#"]*(w+2)]+[["#"]+list(input())+["#"] for _ in range(h)]+[["#"]*(w+2)]
import copy

def f(i,j):
  arr = []
  if done[i][j+1] == 0 and maze[i][j+1] == ".":
    arr.append([i,j+1])
    done[i][j+1] = 1
  if done[i][j-1] == 0 and maze[i][j-1] == ".":
    arr.append([i,j-1])
    done[i][j-1] = 1
  if done[i+1][j] == 0 and maze[i+1][j] == ".":
    arr.append([i+1,j])
    done[i+1][j] = 1
  if done[i-1][j] == 0 and maze[i-1][j] == ".":
    arr.append([i-1,j])
    done[i-1][j] = 1
  return arr

ans = 0
#print(maze)
for i in range(1,h+1):
  for  j in range(1,w+1):
    if maze[i][j] == "#":
      continue
    done = [[1]*(w+2)]+[[1]+[0]*w +[1] for _ in range(h)]+[[1]*(w+2)]
    next_wait = [[i,j]]
    done[i][j] == 1
    cnt = 0
    while next_wait:
      wait = copy.copy(next_wait)
      next_wait = []
      #print(wait)
      while wait:
        now = wait.pop()
        next_wait += f(now[0],now[1])
      cnt += 1
    ans = max(ans,cnt)
print(max(0,ans-1))

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())
maze = []
for i in range(N):
    maze.append(list(input()))
INF = -1
cost = [[INF]*M for _ in range(N)]
dx = [1,0,-1,0]
dy = [0,1,0,-1]
sx,sy = 0,0
gx,gy = 0,0
"""
for i in range(len(maze)):
    if "S" in maze[i]:
        sx = i
        sy = maze[i].index("S")
    if "G" in maze[i]:
        gx = i
        gy = maze[i].index("G")
    else:
        continue
"""
sf = False
gf = False
for i in range(N):
    if sf:
        break
    for j in range(M):
        if sf:
            break
        if maze[i][j] != "#":
            sx,sy = i,j
            sf = True
for i in range(N-1,-1,-1):
    if gf:
        break
    for j in range(M-1,-1,-1):
        if gf:
            break
        if maze[i][j] != "#":
            gx,gy = i,j
            gf = True
def bfs():
    P = deque()
    P.append([sx,sy])
    cost[sx][sy] = 0
    while len(P) != 0:
        p = P.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < N and 0 <= ny < M and maze[nx][ny] != "#" and cost[nx][ny] == INF:
                P.append([nx,ny])
                cost[nx][ny] = cost[p[0]][p[1]]+1
    return cost[gx][gy]
bfs()

ans = 0
for i in cost:
    if ans < max(i):
        ans = max(i)

cost = [[INF]*M for _ in range(N)]
sf = False
gf = False
for i in range(N-1,-1,-1):
    if sf:
        break
    for j in range(M):
        if sf:
            break
        if maze[i][j] != "#":
            sx,sy = i,j
            sf = True
for i in range(N):
    if gf:
        break
    for j in range(M-1,-1,-1):
        if gf:
            break
        if maze[i][j] != "#":
            gx,gy = i,j
            gf = True
bfs()
for i in cost:
    if ans < max(i):
        ans = max(i)

print(ans)

Submission status: Wrong Answer

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

inf=100000000
ma=[]
for i in range(h):
    for j in range(w):
        x=[[inf for i_sub in range(w)] for j_sub in range(h)]
        q=queue.Queue()
        d=0
        q.put([i,j])
        x[i][j]=0
        while q.qsize()!=0:
            d+=1
            l=q.qsize()
            for t in range(l):
                I,J=q.get()
                if I-1>=0 and s[I-1][J]=="." and x[I-1][J]==inf:
                    q.put([I-1,J])
                    x[I-1][J]=d
                if I+1<=h-1 and s[I+1][J]=="." and x[I+1][J]==inf:
                    q.put([I+1,J])
                    x[I+1][J]=d
                if J-1>=0 and s[I][J-1]=="." and x[I][J-1]==inf:
                    q.put([I,J-1])
                    x[I][J-1]=d
                if J+1<=w-1 and s[I][J+1]=="." and x[I][J+1]==inf:
                    q.put([I,J+1])
                    x[I][J+1]=d
        ma_sub=0
        for k in range(h):
            for l in range(w):
                if x[k][l]!=inf:
                    ma_sub=max(ma_sub,x[k][l])
        ma.append(ma_sub)
print(max(ma))

Submission status: Wrong Answer

Solution code:
from collections import deque

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


def bfs(h, w, s, s_h, s_w):
    if s[s_h][s_w] == '#':
        return 0
    d_max = 0
    pas = [[-1 for _ in range(w)] for _ in range(h)]
    dist = [[-1 for _ in range(w)] for _ in range(h)]
    dist[s_h][s_w], pas[s_h][s_w] = 0, 's'
    que = deque()
    que.append((s_h, s_w))
    while len(que) > 0:
        q = que.popleft()
        near = [(q[0]+1, q[1]), (q[0], q[1]+1), (q[0]-1, q[1]), (q[0], q[1]-1)]
        for i in near:
            if (i[0] < 0) | (i[0] >= h) | (i[1] < 0) | (i[1] >= w):
                continue
            if (dist[i[0]][i[1]] == -1) & (s[i[0]][i[1]] == '.'):
                dist[i[0]][i[1]] = dist[q[0]][q[1]] + 1
                pas[i[0]][i[1]] = q
                que.append(i)
                d_max = max(dist[q[0]][q[1]] + 1, d_max)
    return d_max


dmax = 0
for i in range(h):
    for j in range(w):
        dist = bfs(h, w, s, i, j)
        dmax = max(dmax, dist)
print(dmax)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=map(int,input().split())
a=[input() for _ in range(h)]
ans=0
for y in range(h):
    for x in range(w):
        b=[[0]*w for _ in range(h)]
        if a[y][x]=="#":
            break
        now=deque([(y,x)])
        while len(now)!=0:
            Y,X=now.popleft()
            for i,j in [[0,1],[0,-1],[1,0],[-1,0]]:
                if 0<=Y+i<=h-1 and 0<=X+j<=w-1:
                    if a[Y+i][X+j]=="." and b[Y+i][X+j]==0:
                        b[Y+i][X+j]=b[Y][X]+1
                        now.append((Y+i,X+j))
        c=0                
        for i in b:
            d=max(i)
            c=max(d,c)
        ans=max(ans,c)     
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
from collections import defaultdict
 
H,W=map(int, sys.stdin.readline().split())
S=[ sys.stdin.readline().strip() for _ in range(H) ]
 
D=[(1,0),(-1,0),(0,1),(0,-1)]
 
def bfs(start):
    Visit={}
    q=deque()
    q.append(start)
    Visit[start]=1
    L=defaultdict(lambda: float("inf"))    #距離
    L[start]=0
 
    while q:
        fro_x,fro_y=q.popleft()
        for dx,dy in D:
            to_x=fro_x+dx
            to_y=fro_y+dy
            if 0<=to_x<H and 0<=to_y<W:
                if S[to_x][to_y]=="." and (to_x,to_y) not in Visit:
                    Visit[to_x,to_y]=1
                    L[(to_x,to_y)]=min(L[(to_x,to_y)],L[(fro_x,fro_y)]+1)
                    q.append((to_x,to_y))
        return max(L.values())
 
ans=0
for h in range(H):
    for w in range(W):
        ans=max(ans,bfs((h,w)))
 
print ans

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
sys.setrecursionlimit(10**8)
H, W = map(int, input().split())
maze = []
for i in range(H):
    tmp = list(input())
    maze.append(tmp[:])

def dfs(i, j, cnt):
    if i < 0 or j < 0 or i > H-1 or j > W-1 or maze[i][j] == "#" or visited[i][j]:
        # top.append(cnt)
        return
    if maze[i][j] == "g":
        top.append(cnt)
    
    visited[i][j] = True
    cnt += 1
    dfs(i+1, j, cnt)
    dfs(i-1, j, cnt)
    dfs(i, j+1, cnt)
    dfs(i, j-1, cnt)

ans = -1
for sx in range(H):
    for sy in range(W):
        for ex in range(H):
            for ey in range(W):
                if maze[sx][sy] == "#" or maze[ex][ey] == "#":
                    continue
                if sx == ex or sy == ey:
                    continue
                maze[ex][ey] = "g"
                top = []
                visited = [[False for _ in range(W)] for _ in range(H)]
                dfs(sx, sy, 0)
                # print(top)
                maze[ex][ey] = "."
                ans = max(ans, max(top))
print(ans)

Submission status: Wrong Answer

Solution code:
h, w = map(int,input().split())
grid = []
grid.append('#' * (w+2))
for _ in range(h):
    grid.append('#' + input().rstrip() + '#')
grid.append('#' * (w+2))
            
from collections import deque
import sys
sys.setrecursionlimit(1000000)


def flatten_2dim(array):
    return [item for sublist in array for item in sublist]

maxstep = 0

step = [[-1] * (w+2) for _ in range(h+2)]
def bfs():
    global maxstep

    dy = [1, 0, -1, 0]
    dx = [0, 1, 0, -1]
    
    que = deque([])
    que.append((s_y, s_x))
    step[s_y][s_x] = 0
    
    while que:
        y, x = que.popleft()

        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if step[ny][nx] == -1 and grid[ny][nx] != "#":
                que.append((ny, nx))
                step[ny][nx] = step[y][x] + 1

    maxstep = max(max(flatten_2dim(step)), maxstep)
    
for i in range(h+2):
    for j in range(w+2):
        if grid[i][j] == ".":
            s_y, s_x = i, j
            bfs()
            break

print(maxstep)

Submission status: Wrong Answer

Solution code:
import queue
import copy

def sgmake(lst):
    for i in range(H):
        for j in range(W):
            if i != j:
                lst.append((i, j))

def bfs(s1,s2, g1, g2):
    cs = copy.deepcopy(s)
    cs[g1][g2] = 'g'
    queueX = queue.Queue()
    queueY = queue.Queue()
    queueX.put(s1)
    queueY.put(s2)
    cs[s1][s2] = 0
    gx = 'Fail'
    gy = 'Fail'
    while queueX.empty() == False:
        x = queueX.get()
        y = queueY.get()

        for i in range(4):
            nextX = x + moveR[i]
            nextY = y + moveC[i]
            if 0 <= nextX and nextX < H\
                and 0 <= nextY and nextY < W\
                and cs[nextX][nextY] != '#'\
                and cs[nextX][nextY] == '.':
                cs[nextX][nextY] = cs[x][y] + 1
                queueX.put(nextX)
                queueY.put(nextY)

            if 0 <= nextX and nextX < H\
                and 0 <= nextY and nextY < W\
                and cs[nextX][nextY] == 'g':
                cs[nextX][nextY] = cs[x][y] + 1
                gx = nextX
                gy = nextY

    if gx != False:
        return cs[gx][gy]
    else:
        return 0

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

moveR = [0, 1, -1, 0]
moveC = [1, 0, 0, -1]
ans = 0
slst = []
glst = []
sgmake(slst)
sgmake(glst)
for i in slst:
    for j in glst:
        if i != j:
            if s[i[0]][i[1]] != '#' and s[j[0]][j[1]] != '#':
                tmp = bfs(i[0], i[1], j[0], j[1])
                ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:

from collections import deque
from copy import deepcopy


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

step=[[1,0],[-1,0],[0,1],[0,-1]]

mx=0
for h in range(H):
    for w in range(W):
        if S[h][w]=="#":continue
        chk=deepcopy(S)
        q=deque([[h,w,0]])
        chk[h][w]="#"
        while q:
            y,x,c=q.popleft()
            for dh,dw in step:
                if y+dh<0 or y+dh>=H:continue
                if x+dw<0 or x+dw>=W:continue
                if chk[y+dh][x+dw]==".":
                    c+=1
                    chk[y+dh][x+dw]="#"
                    q.append([y+dh,x+dw,c])
                    mx=max(mx,c)

print(mx)

Submission status: Wrong Answer

Solution code:
H,W = map(int,input().split())
S = []
for h in range(H):
    S.append(input())
from collections import deque
ans = 0
for h in range(H):
    for w in range(W):
        Q = deque([[h,w]])
        count_map = [[-1 for _ in range(W)] for __ in range(H)]
        count_map[h][w] = 0
        while Q:
            q = Q.popleft()
            cnt = count_map[q[0]][q[1]] + 1
            if q[0]-1 >= 0:#上
                if S[q[0]-1][q[1]] == "." and count_map[q[0]-1][q[1]] == -1:
                    count_map[q[0]-1][q[1]] = cnt
                    Q.append([q[0]-1,q[1]])
            if q[1]-1 >= 0:#左
                if S[q[0]][q[1]-1] == "." and count_map[q[0]][q[1]-1] == -1:
                    count_map[q[0]][q[1]-1] = cnt
                    Q.append([q[0],q[1]-1])
            if q[0]+1 <= H-1:#下
                if S[q[0]+1][q[1]] == "." and count_map[q[0]+1][q[1]] == -1:
                    count_map[q[0]+1][q[1]] = cnt
                    Q.append([q[0]+1,q[1]])
            if q[1]+1 <= W-1:#右
                if S[q[0]][q[1]+1] == "." and count_map[q[0]][q[1]+1] == -1:
                    count_map[q[0]][q[1]+1] = cnt
                    Q.append([q[0],q[1]+1])
        temp_max = 0
        for cm in count_map:
            temp_max = max(temp_max,max(cm))
        ans = max(ans,temp_max)
print(ans)

Submission status: Wrong Answer

Solution code:
import queue
import itertools
r,c=map(int,input().split())
s=[list(input()) for i in range(r)]
ans=0
for i1 in range(r):
    for i2 in range(c):
        for j1 in range(r):
            for j2 in range(c):
                a=[[s[j][i] for i in range(c)] for j in range(r)]
                sy,sx=i1,i2
                gy,gx=j1,j2
                if a[sy][sx]=="#" or a[gy][gx]=="#":
                    break
                #print(sy,sx,gy,gx)
                q = queue.Queue()
                d=[(-1,0),(1,0),(0,-1),(0,1)]
                a[sy][sx]=0
                for i in d:
                    if 0<=sy+i[0]<r and 0<=sx+i[1]<c and a[sy+i[0]][sx+i[1]]==".":
                        a[sy+i[0]][sx+i[1]]=1
                        q.put((sy+i[0],sx+i[1]))
                while not q.empty():
                    y,x=q.get()
                    for i in d:
                        if 0<=y+i[0]<r and 0<=x+i[1]<c and a[y+i[0]][x+i[1]]==".":
                            a[y+i[0]][x+i[1]]=a[y][x]+1
                            q.put((y+i[0],x+i[1]))
                ans=max(a[gy][gx],ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
def dfs(x,y,z,grid,H,W):
    if(x-1>=0):
        if(grid[y][x-1]>z or grid[y][x-1]==0):
            grid[y][x-1]=z+1
            dfs(x-1,y,z+1,grid,H,W)
    if(x+1<W):
        if(grid[y][x+1]>z or grid[y][x+1]==0):
            grid[y][x+1]=z+1
            dfs(x+1,y,z+1,grid,H,W)
    if(y-1>=0):
        if(grid[y-1][x]>z or grid[y-1][x]==0):
            grid[y-1][x]=z+1
            dfs(x,y-1,z+1,grid,H,W)
    if(y+1<H):
        if(grid[y+1][x]>z or grid[y+1][x]==0):
            grid[y+1][x]=z+1
            dfs(x,y+1,z+1,grid,H,W)
    return 0


H,W=map(int,input().split())
grid=[]
tmp=[]
for i in range(H):
    S=str(input())
    tmp=[]
    for j in range(W):
        if(S[j]=="."):
            tmp.append(0)
        else:
            tmp.append(-1)
    grid.append(tmp)
ans=0
result=0
for i in range(W):
    for j in range(H):
        if(grid[j][i]==0):
            dataset=copy.deepcopy(grid)
            dfs(i,j,1,dataset,H,W)
            ans=max(dataset)
            ans=max(ans)
            result=max(result,ans)
print(result-1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
sys.setrecursionlimit(10**8)
H, W = map(int, input().split())
maze = []
for i in range(H):
    tmp = list(input())
    maze.append(tmp[:])

def dfs(i, j, cnt):
    if i < 0 or j < 0 or i > H-1 or j > W-1 or maze[i][j] == "#" or visited[i][j]:
        # top.append(cnt)
        return
    if maze[i][j] == "g":
        top.append(cnt)
    
    visited[i][j] = True
    cnt += 1
    dfs(i+1, j, cnt)
    dfs(i-1, j, cnt)
    dfs(i, j+1, cnt)
    dfs(i, j-1, cnt)

ans = -1
for sx in range(H):
    for sy in range(W):
        for ex in range(H):
            for ey in range(W):
                if maze[sx][sy] == "#" or maze[ex][ey] == "#":
                    continue
                if sx == ex or sy == ey:
                    continue
                maze[ex][ey] = "g"
                top = []
                visited = [[False for _ in range(W)] for _ in range(H)]
                dfs(sx, sy, 0)
                # print(top)
                ans = max(ans, max(top))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H,W = map(int,input().split())
#A = list(map(int,input().split()))
S = []

def bfs(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 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 0 <=new_y<=H-1 and 0<= new_x<=W-1:
                if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
                    visited[new_y][new_x] = visited[y][x] + 1
                    queue.append([new_y, new_x])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    for i in range(H):
        if maxa in visited[i]:
            ret = [i,visited[i].index(maxa)]
            break
    return ret
def bfs2(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 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 0 <=new_y<=H-1 and 0<= new_x<=W-1:
                if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
                    visited[new_y][new_x] = visited[y][x] + 1
                    queue.append([new_y, new_x])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    return maxa
    

for i in range(H):
    s = list(input())
    S.append(s)
for i in range(H):
    if '.' in S[i]:
        start = [i,S[i].index('.')]
        break
ret = bfs(S,start[0],start[1])
ret = bfs(S,ret[0],ret[1])
ans = bfs2(S,ret[0],ret[1])
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

def search(h, w, pre_h, pre_w):
    can = []
    if h > 0:
        can.append((h-1, w))
    if h < H-1:
        can.append((h+1, w))
    if w > 0:
        can.append((h, w-1))
    if w < W-1:
        can.append((h, w+1))
    res = []
    for h, w in can:
        if S[h][w]=='.' and (h, w) != (pre_h, pre_w):
            res.append((h, w))
    return res

def bfs(h, w):
    d = [[float('inf') for _ in range(W)] for _ in range(H)]
    d[h][w] = 0
    pre_h, pre_w = h, w
    adj_list = search(h, w, pre_h, pre_w)
    open_list = deque([])
    for adj in adj_list:
        open_list.append((adj[0], adj[1], pre_h, pre_w))
    cnt = 0
    while True:
        cnt += 1
        if cnt > H*W**2:
            break
        if len(open_list) == 0:
            break
        h, w, pre_h, pre_w = open_list.popleft()
        d[h][w] = min(d[h][w], d[pre_h][pre_w] + 1)
        adj_list = search(h, w, pre_h, pre_w)
        for adj in adj_list:
            open_list.append((adj[0], adj[1], h, w))

    res = 0
    for h in range(H):
        for w in range(W):
            if not d[h][w] == float('inf'):
                res = max(res, d[h][w])
    return res

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

if __name__ == "__main__":
    ans = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                continue
            maxd = bfs(h, w)
            ans = max(maxd, ans)
    print(ans)

Submission status: Wrong Answer

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

inf=100000000
ma=[]
for i in range(h):
    for j in range(w):
        x=[[inf for i_sub in range(w)] for j_sub in range(h)]
        q=queue.Queue()
        d=-1
        q.put([i,j])
        while q.qsize()!=0:
            d+=1
            l=q.qsize()
            for t in range(l):
                I,J=q.get()
                x[I][J]=d
                if I-1>=0 and s[I-1][J]=="." and x[I-1][J]==inf:
                    q.put([I-1,J])
                if I+1<=h-1 and s[I+1][J]=="." and x[I+1][J]==inf:
                    q.put([I+1,J])
                if J-1>=0 and s[I][J-1]=="." and x[I][J-1]==inf:
                    q.put([I,J-1])
                if J+1<=w-1 and s[I][J+1]=="." and x[I][J+1]==inf:
                    q.put([I,J+1])
        ma_sub=0
        for k in range(h):
            for l in range(w):
                if x[k][l]!=inf:
                    ma_sub=max(ma_sub,x[k][l])
        ma.append(ma_sub)
print(max(ma))

Submission status: Wrong Answer

Solution code:
import copy
import queue

H,W = map(int, input().split())
def check(x,y):
    global W,H
    if x<0 or y<0 or x>=W or y>=H:
        return False
    return True

m = []
visit = []
for _ in range(H):
    S = list(input())
    m.append(S)
    l = [-1]*W
    visit.append(l)

visit_copy = copy.deepcopy(visit)
max = 0

for i in range(H):
    for j in range(W):
        sy = i
        sx = j
        q = queue.Queue()
        visit[sy][sx] = 0
        q.put([sy,sx])
        while not (q.empty()):
            y,x = q.get()
            if m[y][x]=="#":
                continue

            if check(x+1,y)==True:
                if visit[y][x+1]==-1 and m[y][x+1]==".":  
                    visit[y][x+1] = visit[y][x] + 1
                    if visit[y][x+1] > max:
                        max = visit[y][x+1]

                    q.put([y,x+1])
            if check(x,y+1)==True:
                if visit[y+1][x]==-1 and m[y+1][x]==".":  
                    visit[y+1][x] = visit[y][x] + 1
                    if visit[y+1][x] > max:
                        max = visit[y+1][x]

                    q.put([y+1,x])
            if check(x,y-1)==True:
                if visit[y-1][x]==-1 and m[y-1][x]==".":  
                    visit[y-1][x] = visit[y][x] + 1
                    if visit[y-1][x] > max:
                        max = visit[y-1][x]

                    q.put([y-1,x])
            if check(x-1,y)==True:
                if visit[y][x-1]==-1 and m[y][x-1]==".":  
                    visit[y][x-1] = visit[y][x] + 1
                    if visit[y][x-1] > max:
                        max = visit[y][x-1]

                    q.put([y,x-1])
    visit = copy.deepcopy(visit_copy)

print(max)

Submission status: Wrong Answer

Solution code:
import sys
import queue
def I(): return int(sys.stdin.readline())
def LI(): return [int(x) for x in sys.stdin.readline().split()]

d = [[-1,0],[1,0],[0,-1],[0,1]]

H,W = LI()
S = [list(input()) for _ in range(H)]

def bfs(s):
    dist = [[-1]*W for _ in range(H)]
    h,w = s
    dist[h][w] = 0
    que = queue.Queue()
    que.put(s)
    while(not(que.empty())):
        h,w = que.get_nowait()
        for dh,dw in d:
            nh,nw = h+dh,w+dw
            if 0<=nh<H and 0<=nw<W and dist[nh][nw]==-1 and S[nh][nw]=='.':
                dist[nh][nw] = dist[h][w] + 1
                que.put([nh,nw])
    ans = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == '.':
                ans = max(ans,dist[h][w])
    return ans

def main():
    ans = 0
    for h in range(H):
        for w in range(W):
            ans = max(ans,bfs([h,w]))
#            if S[h][w] == '.':
#                if (((h==0 or S[h-1][w]=='#') or (h==H-1 or S[h+1][w]=='#')) and 
#                        ((w==0 or S[h][w-1]=='#') or (w==W-1 or S[h][w+1]=='#'))):
#                    ans = max(ans,bfs([h,w]))
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
H,W = map(int,input().split())
#A = list(map(int,input().split()))
S = []

def bfs(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 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 0 <=new_y<=H-1 and 0<= new_x<=W-1:
                if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
                    visited[new_y][new_x] = visited[y][x] + 1
                    queue.append([new_y, new_x])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    for i in range(H):
        if maxa in visited[i]:
            ret = [i,visited[i].index(maxa)]
            break
    return ret
def bfs2(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 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 0 <=new_y<=H-1 and 0<= new_x<=W-1:
                if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
                    visited[new_y][new_x] = visited[y][x] + 1
                    queue.append([new_y, new_x])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    return maxa
    

for i in range(H):
    s = list(input())
    S.append(s)
for i in range(H):
    if '.' in S[i]:
        start = [i,S[i].index('.')]
        break
ret = bfs(S,start[0],start[1])
ans = bfs2(S,ret[0],ret[1])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
from queue import Queue
h,w=map(int,input().split())
S=[input() for _ in range(h)]

def bfs(q):
  x,y,cnt=q.get()
  if x<0 or x>=w or y<0 or y>=h:
    return
  elif S[y][x]=='#':
    return
  elif memo[y][x]<0:
    memo[y][x]=cnt
    q.put([x-1,y,cnt+1])
    q.put([x+1,y,cnt+1])
    q.put([x,y-1,cnt+1])
    q.put([x,y+1,cnt+1])

ans=0
for x in range(h):
  for y in range(w):
    if x==h//2+1 and y==w//2+1:
      break
    q=Queue()
    q.put([x,y,0])
    memo=[[-1]*w for _ in range(h)]
    while not q.empty():
      bfs(q)
    ans=max(ans,max(max(memo)))
print(ans)

Submission status: Wrong Answer

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

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

maze = np.zeros((H, W))

for i in range(H):
    s = input()
    for j in range(W):
        if s[j] == '.':
            maze[i, j] = 1

max_run = 0

tan = [[1, 0], [-1, 0], [0, 1], [0, -1]]
g = (21, 21)

def max_route(h, w):
    # q = queue.Queue()
    q = deque()
    checker = maze.copy()
    q.append((h, w))
    q.append(g)

    run = 0

    while len(q):
        target = q.popleft()
        if target == g:
            if len(q):
                run += 1
                q.append(g)
        else:
            for t in tan:
                check = [target[0]+t[0], target[1]+t[1]]
                if 0 <= check[0] < H and 0 <= check[1] < W:
                    if checker[check[0], check[1]] == 1:
                        q.append((check[0], check[1]))
                        checker[check[0], check[1]] = 2

    return run


for h in range(H):
    for w in range(W):
        if maze[h, w] == 0:
            continue
        cur = max_route(h, w)
        if cur > max_run:
            max_run = cur

print(max_run)

Submission status: Wrong Answer

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

S = list()
for i in range(H):
  S.append(list(map(lambda x: int(x == '.'), input())))

for i in range(H):
  S[i].append(0)
  S[i].append(0)
S.append([0 for _ in range(W + 2)])

moved = [
  [
    False for w in range(W + 2)
  ]
  for h in range(H + 2)
]

def wfs(loc):
  queue = [(loc, 0)]
  ans = 0
  tgt = not moved[loc[0]][loc[1]]
  not_tgt = not tgt
  moved[loc[0]][loc[1]] = tgt
  while (queue):
    (h, w), move = queue.pop(0)
    for i, j in zip((1, -1, 0, 0), (0, 0, -1, 1)):
      _h, _w = h + i, w + j
      if moved[_h][_w] == not_tgt and S[_h][_w] == 1:
        moved[_h][_w] = tgt
        queue.append(((_h, _w), move + 1))
    ans = max(ans, move)
  return ans

ans = 0
for i in range(H):
  for j in range(W):
    ans = max(ans, wfs((i, j)))
print(ans)

Submission status: Wrong Answer

Solution code:
INFTY = 1000
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
G = {(i,j):[] for i in range(H) for j in range(W)}
for i in range(H):
    for j in range(W):
        if j+1<W and S[i][j+1]==".":
            G[(i,j)].append((i,j+1))
        if j-1>-1 and S[i][j-1]==".":
            G[(i,j)].append((i,j-1))
        if i+1<H and S[i+1][j]==".":
            G[(i,j)].append((i+1,j))
        if i-1>-1 and S[i-1][j]==".":
            G[(i,j)].append((i-1,j))
d = {(i,j):{(k,l):INFTY for k in range(H) for l in range(W)} for i in range(H) for j in range(W)}
for i in range(H):
    for j in range(W):
        for x in G[(i,j)]:
            k,l = x[0],x[1]
            d[(i,j)][(k,l)] = 1
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                for m in range(H):
                    for n in range(W):
                        d[(k,l)][(m,n)]=min(d[(k,l)][(m,n)],d[(k,l)][(i,j)]+d[(i,j)][(m,n)])
cmax = 0
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                if d[(i,j)][(k,l)]<INFTY:
                    cmax = max(cmax,d[(i,j)][(k,l)])
print(cmax)

Submission status: Wrong Answer

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

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

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


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


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