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:
from itertools import permutations
from collections import deque
INFTY = 10**3
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
cmax = 0
for x in permutations(range(H),2):
    for y in permutations(range(W),2):
        if S[x[0]][y[0]]=="." and S[x[1]][y[1]]==".":
            A = [[INFTY for _ in range(W)] for _ in range(H)]
            hist = {(i,j):0 for i in range(H) for j in range(W)}
            que = deque([(x[0],y[0],0)])
            A[x[0]][y[0]] = 0
            hist[(x[0],y[0])] = 1
            while que:
                i,j,d = que.popleft()
                if j+1<W and S[i][j+1]=="." and hist[(i,j+1)]==0:
                    A[i][j+1]=d+1
                    hist[(i,j+1)]=1
                    que.append((i,j+1,d+1))
                if i-1>=0 and S[i-1][j]=="." and hist[(i-1,j)]==0:
                    A[i-1][j]=d+1
                    hist[(i-1,j)]=1
                    que.append((i-1,j,d+1))
                if j-1>=0 and S[i][j-1]=="." and hist[(i,j-1)]==0:
                    A[i][j-1]=d+1
                    hist[(i,j-1)]=1
                    que.append((i,j-1,d+1))
                if i+1<H and S[i+1][j]=="." and hist[(i+1,j)]==0:
                    A[i+1][j]=d+1
                    hist[(i+1,j)]=1
                    que.append((i+1,j,d+1))
            cmax = max(cmax,A[x[1]][y[1]])
print(cmax)

Submission status: Wrong Answer

Solution code:
from collections import deque
def bfs(y,x):
  q=deque([(y,x)])
  while q:
    cy,cx=q.popleft()
    for dy,dx in [(1,0),(-1,0),(0,1),(0,-1)]:
      ny,nx=cy+dy,cx+dx
      if 0<=ny<h and 0<=nx<w and visited[ny][nx]==0:
        if s[ny][nx]=="#":continue
        visited[ny][nx]=visited[cy][cx]+1
        q.append((ny,nx))
  res=0
  for i in range(h):
    for j in range(w):
      if s[i][j]!="#":
        res=max(res,visited[i][j])
  return res

h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=0
for i in range(h):
  for j in range(w):
    if s[i][j]=="#":continue
    sh=i
    sw=j
    visited=[[0]*w for _ in range(h)]
    ans=max(ans,bfs(sh,sw))
print(ans)

Submission status: Wrong Answer

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

for ix in range(H):
    S.append(list(input()))


Dt = [(0,1), (1,0), (-1, 0), (0, -1)]
ans = 0
for x in range(H):
    for y in range(W):

        if S[x][y] == '#':
            continue
        # traverse
        sp = (x, y, 0)
        q = [sp]
        mxp = 0
        DP = [[0 for _ in range(W+1)] for __ in range(H+1)]

        while len(q) != 0:

            x, y, p = q[0]
            q.pop(0)

            if DP[x][y] != 0:
                continue
            else:
                DP[x][y] = 1

            if p > ans:
                ans = p

            for d in Dt:
                nx = x + d[0]
                ny = y + d[1]

                if nx < 0 or ny < 0 or nx >= H or ny >= W or S[nx][ny] == '#':
                    continue

                q.append((nx, ny, p + 1))

print(ans)

Submission status: Wrong Answer

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

for ix in range(H):
    S.append(list(input()))


Dt = [(0,1), (1,0), (-1, 0), (0, -1)]
ans = 0
for x in range(H):
    for y in range(W):

        if S[x][y] == '#':
            continue
        # traverse
        sp = (x, y, 0)
        q = [sp]
        mxp = 0
        DP = [[0 for _ in range(W+1)] for __ in range(H+1)]

        while len(q) != 0:

            x, y, p = q[0]
            q.pop(0)

            if DP[x][y] != 0:
                continue
            else:
                DP[x][y] = 1

            if p > mxp:
                mxp = p

            for d in Dt:
                nx = x + d[0]
                ny = y + d[1]

                if nx < 0 or ny < 0 or nx >= H or ny >= W or S[nx][ny] == '#':
                    continue

                q.append((nx, ny, p + 1))

        if ans < mxp:
            ans = mxp

print(ans)

Submission status: Wrong Answer

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

for ix in range(H):
    S.append(list(input()))


Dt = [(0,1), (1,0), (-1, 0), (0, -1)]
ans = 0
for x in range(H):
    for y in range(W):

        if S[x][y] == '#':
            continue
        # traverse
        sp = (x, y, 0)
        q = [sp]
        mxp = -1
        DP = [[0 for _ in range(W+1)] for __ in range(H+1)]

        while len(q) != 0:

            x, y, p = q[0]
            q.pop(0)

            if DP[x][y] != 0:
                continue
            else:
                DP[x][y] = 1

            if p > mxp:
                mxp = p

            for d in Dt:
                nx = x + d[0]
                ny = y + d[1]
                np = p + 1

                if nx < 0 or ny < 0 or nx >= H or ny >= W or S[nx][ny] == '#':
                    continue

                q.append((nx, ny, np))
            

        if ans < mxp:
            ans = mxp

print(ans)

Submission status: Wrong Answer

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

for ix in range(H):
    S.append(list(input()))


Dt = [(0,1), (1,0), (-1, 0), (0, -1)]
ans = -1
for x in range(H):
    for y in range(W):

        # traverse
        sp = (x, y, 0)
        q = [sp]
        mxp = -1
        DP = [[0 for _ in range(W+1)] for __ in range(H+1)]

        while len(q) != 0:

            x, y, p = q[0]
            q.pop(0)

            if DP[x][y] != 0:
                continue
            else:
                DP[x][y] = 1

            if p > mxp:
                mxp = p

            for d in Dt:
                nx = x + d[0]
                ny = y + d[1]
                np = p + 1

                if nx < 0 or ny < 0 or nx >= H or ny >= W or S[nx][ny] == '#':
                    continue

                q.append((nx, ny, np))
            

        if ans < mxp:
            ans = mxp

print(ans)

Submission status: Wrong Answer

Solution code:
from queue import Queue
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
def main():
    h, w = [int(x) for x in input().split()]
    grid = []

    for _ in range(h):
        linha = [x for x in input()]
        grid.append(linha)

    resp = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == '.':
                resp = max(resp, BFS(i, j, grid, h, w, [[False]*w for _ in range(h)]))

    print(resp)
    
def BFS(x, y, grafo, h, w, passou):

    fila = Queue()
    fila.put((0, x, y))
    
    while not fila.empty():
        c, x, y = fila.get()

        for i in range(4):
            if 0 <= x + dx[i] < h and 0 <= y + dy[i] < w and grafo[x + dx[i]][y + dy[i]] == '.' and not passou[x + dx[i]][y + dy[i]]:
                fila.put((c + 1, x + dx[i], y + dy[i]))
                passou[x + dx[i]][y + dy[i]] = True
                
    return c

main()

Submission status: Wrong Answer

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

def bfs(sy, sx):
    mx=0
    q=Queue()
    dist=[[-1]*W for _ in range(H)]
    q.put((sy,sx))
    dist[sy][sx]=0
    while not q.empty():
        y, x=q.get()
        y_nxt=[y+1, y-1, y, y]
        x_nxt=[x, x, x+1, x-1]
        for Y,X in zip(y_nxt, x_nxt):
            if not (0 <= Y < H) or not (0 <= X < W) or S[Y][X]=="#":
                continue
            if dist[Y][X]==-1:
                dist[Y][X]=dist[y][x]+1
                q.put((Y, X))
                mx=max(mx, dist[Y][X])
    return mx

mx=0
for y in range(H):
    for x in range(W):
        mx=max(bfs(y,x),mx)

print(mx)

Submission status: Wrong Answer

Solution code:
from collections import Counter, defaultdict
import sys

sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
from copy import deepcopy
import queue
from collections import deque


def maxload(data_copy, i, j, high, width):
    data = deepcopy(data_copy)
    count = 0
    now_point = set()
    now_point.add((i, j))
    next_point = set()

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

    while len(now_point):
        for now_i, now_j in now_point:
            data[now_i][now_j] = count
            for move_i, move_j in move:
                next_i, next_j = now_i + move_i, now_j + move_j
                if next_i < 0 or next_i >= high or next_j < 0 or next_j >= width:
                    continue
                if data[next_i][next_j] != ".":
                    continue
                next_point.add((next_i, next_j))

        now_point = next_point
        next_point = set()
        count += 1

    return count - 1



def main():
    high, width = map(int, input().split())
    data = [list(input()) for i in range(high)]

    ans = 0

    for i in range(high):
        for j in range(width):
            ans = max(ans, maxload(data, i, j, high, width))
            # print(ans, data)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import Counter, defaultdict
import sys

sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
from copy import deepcopy
import queue
from collections import deque


def minload(data_copy, high_i, width_i, high_j, width_j, high, width):
    data = deepcopy(data_copy)
    count = 0
    now_point = set()
    now_point.add((high_i, width_i))
    next_point = set()
    goal = [high_j, width_j]
    move = [[1, 0], [0, 1], [-1, 0], [0, -1]]

    while 1:
        for now_i, now_j in now_point:
            data[now_i][now_j] = count
            for move_i, move_j in move:
                next_i, next_j = now_i + move_i, now_j + move_j
                if next_i < 0 or next_i >= high or next_j < 0 or next_j >= width:
                    continue
                if data[next_i][next_j] != ".":
                    continue
                # data[next_i][next_j] = count
                next_point.add((next_i, next_j))

        if data[goal[0]][goal[1]] != ".":
            break
        now_point = next_point
        next_point = set()
        count += 1

    # print(data)

    return data[goal[0]][goal[1]]



def main():
    high, width = map(int, input().split())
    data = [list(input()) for i in range(high)]

    ans = 0

    for high_i in range(high):
        for width_i in range(width):
            for high_j in range(high_i, high):
                for width_j in range(width_i, width):
                    # print(high_i, width_i, high_j, width_j)
                    if high_i == high_j and width_i == width_j:
                        continue
                    if data[high_i][width_i] == data[high_j][width_j] == ".":
                        ans = max(ans, minload(data, high_i, width_i, high_j, width_j, high, width))
                        # print(ans, data)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from math import ceil,floor,comb,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

def bfs():
    d = [[inf]*w for i in range(h)]

    dy = [0, 1, 0, -1] 
    dx = [1, 0, -1, 0]
 
    que = deque([])
    que.append((sy, sx))
    d[sy][sx] = 0
 
    while que:
        p = que.popleft()
        if p[0] == gy and p[1] == gx:
            break
        for i in range(4):
            ny = p[0] + dy[i]
            nx = p[1] + dx[i]
 
            if 0 <= ny < h and 0 <= nx < w and maze[ny][nx] != '#' and d[ny][nx] == inf:
                que.append((ny,nx))
                d[ny][nx] = d[p[0]][p[1]] + 1
 
    return d[gy][gx]

h, w = MAP()
maze = [input() for i in range(h)]
ans = 0

for sy in range((h+1)//2):
    for sx in range(w):
        for gy in range((h+1)//2, h):
            for gx in range(w):
                if (sy == gy and sx == gx) or maze[sy][sx] == '#' or maze[gy][gx] == '#':
                    continue
                else:
                    ans = max(ans, bfs())

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
field = ''
for i in range(H):
    field += input()

def bfs(start):
    dist = [0] * (H * W)
    q = deque([start])
    while q:
        p = q.popleft()
        c = dist[p] + 1
        print(p)
        if p % W == 0:
            nex_li = [p-W, p+W, p+1]
        elif p % W == W - 1:
            nex_li = [p-W, p+W, p-1]
        else:
            nex_li = [p-W, p+W, p-1, p+1]
        for nex in nex_li:
            if nex != start and nex >= 0 and nex < H * W and field[nex] == '.':
                dist[nex] = c
                q.append(nex)
    return dist[p]

ans = 0
for s in range(H * W):
    if field[s] == '.':
        ans = max(ans, bfs(s))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
field = ''
for i in range(H):
    field += input()

def bfs(start):
    dist = [0] * (H * W)
    q = deque([start])
    while q:
        p = q.popleft()
        c = dist[p] + 1
        if p - W >= 0 and field[p - W] == '.' and dist[p - W] == 0:
            dist[p - W] = c
            q.append(p - W)
        if p + W < H * W and field[p + W] == '.' and dist[p + W] == 0:
            dist[p + W] = c
            q.append(p + W)
        if p - 1 >= 0 and field[p - 1] == '.' and dist[p - 1] == 0 and p % W != 0:
            dist[p - 1] = c
            q.append(p - 1)
        if p + 1 < H * W and field[p + 1] == '.' and dist[p + 1] == 0 and p % W != W - 1:
            dist[p + 1] = c
            q.append(p + 1)
    return dist[p]

ans = 0
for s in range(H * W):
    if field[s] == '.':
        ans = max(ans, bfs(s))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
field = ''
for i in range(H):
    field += input()

def bfs(start):
    dist = [0] * (H * W)
    q = deque([start])
    while q:
        p = q.popleft()
        c = dist[p] + 1
        if p - W >= 0 and field[p - W] == '.' and dist[p - W] == 0:
            dist[p - W] = c
            q.append(p - W)
        if p + W < H * W and field[p + W] == '.' and dist[p + W] == 0:
            dist[p + W] = c
            q.append(p + W)
        if p - 1 >= 0 and field[p - 1] == '.' and dist[p - 1] == 0 and p % W != 0:
            dist[p - 1] = c
            q.append(p - 1)
        if p + 1 < H * W and field[p + 1] == '.' and dist[p + 1] == 0 and p % W != W - 1:
            dist[p + 1] = c
            q.append(p + 1)
    return dist[p]

ans = -1
for s in range(H * W):
    if field[s] == '.':
        ans = max(ans, bfs(s))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
field = [['#'] * (W + 2)]
for i in range(H):
    field.append(list('#' + input() + '#'))
field.append(['#'] * (W + 2))

def num_to_coo(p):
    h, w = divmod(p, W)
    h += 1
    w += 1
    return h, w

def bfs(s):
    cost = [-1] * (H * W)
    q = deque()
    q.append((s, 0))
    while q:
        p, c = q.popleft()
        cost[p] = c
        h, w = num_to_coo(p)
        if (field[h - 1][w] == '.') and p - W >= 0 and (cost[p - W] == -1):
            q.append((p - W, c + 1))
        if (field[h + 1][w] == '.') and p + W < H * W and (cost[p + W] == -1):
            q.append((p + W, c + 1))
        if (field[h][w - 1] == '.') and p - 1 >= 0 and (cost[p - 1] == -1):
            q.append((p - 1, c + 1))
        if (field[h][w + 1] == '.') and p + 1 < H * W and (cost[p + 1] == -1):
            q.append((p + 1, c + 1))
    return c

ans = -1
for s in range(H * W):
    ans = max(ans, bfs(s))
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
H, W = map(int, input().split())
map_lis = [input() for i in range(H)]
ans = 0

def prob(x,y,h,w):
  if 0<=x<h and 0<=y<w:
    return True
  else:
    return False

def count(x,y,lis):
  if not lis[x][y]:
    return True
  else:
    return False

def maze(x,y,lis):
  if lis[x][y] == ".":
    return True
  else:
    return False

for i in range(H):
  for j in range(W):
    k = 0
    count_lis = np.zeros((H,W))
    num_lis = [[] for i in range(1000)]
    num_lis[0].append([i,j])
    while True:
      for l in num_lis[k]:
        if prob(l[0]-1,l[1],H,W) and count(l[0]-1,l[1],count_lis) and maze(l[0]-1,l[1],map_lis):
          num_lis[k+1].append([l[0]-1,l[1]])
          count_lis[l[0]-1][l[1]] = 1
        if prob(l[0],l[1]-1,H,W) and count(l[0],l[1]-1,count_lis) and maze(l[0],l[1]-1,map_lis):
          num_lis[k+1].append([l[0],l[1]-1])
          count_lis[l[0]][l[1]-1] = 1
        if prob(l[0]+1,l[1],H,W) and count(l[0]+1,l[1],count_lis) and maze(l[0]+1,l[1],map_lis):
          num_lis[k+1].append([l[0]+1,l[1]])
          count_lis[l[0]+1][l[1]] = 1
        if prob(l[0],l[1]+1,H,W) and count(l[0],l[1]+1,count_lis) and maze(l[0],l[1]+1,map_lis):
          num_lis[k+1].append([l[0],l[1]+1])
          count_lis[l[0]][l[1]+1] = 1
      if num_lis[k+1] == []:
        break
      new_ans = 0
      for m in num_lis[1:]:
        if m != []:
          new_ans += 1
        if m == []:
          break
      ans = max(ans, new_ans)
      k += 1
    
                                           
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

dist = [[-1] * W for _ in range(H)]

def BFS(y, x):
  """(y, x)からはじめて、道のマスをBFSで最短距離を探す"""
  que = deque()
  que.append((y, x))
  dist[y][x] = 0
  max_dist = 0
  while que:
    sy, sx = que.popleft()  # popleft?
    for dy, dx in dir:
      ny = sy + dy
      nx = sx + dx
      if 0 <= ny < H and 0 <= nx < W and S[ny][nx] != "#" and dist[ny][nx] == -1:
        que.append((ny, nx))
        dist[ny][nx] = dist[sy][sx] + 1
        max_dist = max(max_dist, dist[ny][nx])
  
  return max_dist

max_dist = 0
for sy in range(H):
  for sx in range(W):
    dist = [[-1] * W for _ in range(H)]
    max_dist = max(max_dist, BFS(sy, sx))

print(max_dist)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

dist = [[-1] * W for _ in range(H)]

def BFS(y, x):
  """(y, x)からはじめて、道のマスをBFSで最短距離を探す"""
  que = deque()
  que.append((y, x))
  dist[y][x] = 0
  
  while que:
    sy, sx = que.popleft()  # popleft?
    for dy, dx in dir:
      ny = sy + dy
      nx = sx + dx
      if 0 <= ny < H and 0 <= nx < W and S[ny][nx] != "#" and dist[ny][nx] == -1:
        que.append((ny, nx))
        dist[ny][nx] = dist[sy][sx] + 1
  

max_dist = 0
for sy in range(H):
  for sx in range(W):
    dist = [[-1] * W for _ in range(H)]
    BFS(sy, sx)
    max_dist = max(max_dist, max(max(dist)))

print(max_dist)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W=map(int,input().split())
S=[]
for i in range(H):
  S.append(input())
  
def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  now = s
  if S[now[0]][now[1]]=='#':return 0
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='#':continue
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return max(map(max, total))

MAX=0
for i in range(H):
  for j in range(W):
    if i*j != 0 and (i!=H-1 and j!=W-1):continue
    s = (i,j)
    max_ = bfs(s)
    if MAX < max_:MAX=max_

print(MAX)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W=map(int,input().split())
S=[]
for i in range(H):
  S.append(input())
  
def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  now = s
  if S[now[0]][now[1]]=='#':return 0
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='#':continue
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return max(map(max, total))

MAX=0
for i in range(H):
  for j in range(W):
    if i*j != 0 and (i!=H-1 or j!=W-1):continue
    s = (i,j)
    max_ = bfs(s)
    if MAX < max_:MAX=max_

print(MAX)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W=map(int,input().split())
S=[]
for i in range(H):
  S.append(input())
  
def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  if s <= H-1:now = (s,0)
  else:now = (H-1,s-H+1)
  if S[now[0]][now[1]]=='#':return 0
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='#':continue
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return max(map(max, total))

MAX=0
for s in range(H+W-1):
  max_ = bfs(s)
  if MAX < max_:MAX=max_

print(MAX)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W=map(int,input().split())
S=[]
for i in range(H):
  S.append(input())
  
def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  if s <= H-1:now = (s,0)
  else:now = (H-1,s-H+1)
  if S[now[0]][now[1]]=='#':return 0
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='#':continue
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return max(map(max, total))

MAX=0
for s in range(H+W-1):
  max_ = bfs(s)
  print(s,max_)
  if MAX < max_:MAX=max_

print(MAX)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
chiz = [[] for _ in range(w)]
for _ in range(h):
    tmp_list = input()
    for i in range(w):
        chiz[i].append(tmp_list[i])
def bfs(i,j):
    ds = [[-1]*h for _ in range(w)]
    dq = deque([(i,j)])
    ds[i][j] = 0
    res = -1
    while dq:
        i,j = dq.popleft()
        for move in [(1,0),(-1,0),(0,-1),(0,1)]:
            if i+move[0] >= 0 and i+move[0] < w and j+move[1] >= 0 and j+move[1] < h:
                if chiz[i+move[0]][j+move[1]]=='.' and ds[i+move[0]][j+move[1]] == -1:
                    ds[i + move[0]][j + move[1]] = ds[i][j] + 1
                    res = max(res,ds[i + move[0]][j + move[1]])
                    dq.append((i + move[0],j + move[1]))
    return res
res = -1
for j in range(h):
    for i in range(w):
        res = max(res, bfs(i,j))
print(res)

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from copy import deepcopy
from collections import deque

h,w=nii()
s=[list(input()) for i in range(h)]

def dfs(cs,i,j):
  que=deque()
  que.append([i,j])

  dist=[[-1 for a in range(w)] for b in range(h)]
  dist[i][j]=0

  while que:
    y,x=que.popleft()
    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and cs[ny][nx]=='.':
        que.append([ny,nx])
        cs[ny][nx]='#'
        dist[ny][nx]=dist[y][x]+1

  t_ans=0
  for a in dist:
    t_ans=max(t_ans,max(a))

  return t_ans

ans=0
for i in range(h):
  for j in range(w):
    if s[i][j]=='.':
      cs=deepcopy(s)
      dist=dfs(cs,i,j)
      ans=max(ans,dist)

print(ans)

Submission status: Wrong Answer

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

import queue, itertools

dxy = ((1,0), (-1,0), (0,1), (0,-1))
ans = 0
for s in itertools.product(range(H), range(W)):
    if S[s[0]][s[1]] == '#': continue
    
    q = queue.Queue()
    dist = [[-1]*W for _ in range(H)]     

    q.put(s)
    while not q.empty():
        y, x = q.get()         
        for dx, dy in dxy:
            nx, ny = x+dx, y+dy
            if nx<0 or ny<0 or nx>=W or ny>=H or S[ny][nx] == '#' or dist[ny][nx] >= 0: 
                continue
            dist[ny][nx] = dist[y][x] + 1
            q.put((ny, nx))
    
    ans = max(ans, max(map(max, dist)))

print(ans+1)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
ma = [ list(input()) for _ in range(h) ]
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
ans = 0

def bfs(sy, sx):
    q = [[sy, sx, 0]]
    flag = [[0] * w for _ in range(h)]
    flag[sy][sx] = 1
    ans = 0
    while True:
        if len(q) == 0:
            break
        y, x, dist = q.pop(0)
        for dy, dx in d:
            if 0 <= y + dy < h and 0 <= x + dx < w and flag[y + dy][x + dx] == 0 and ma[y + dy][x + dx] == ".":
                flag[y + dy][x + dx] = 1
                q.append([y + dy, x + dx, dist + 1])
                ans = max(ans, dist + 1)
    
    return ans


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

print(ans)

Submission status: Wrong Answer

Solution code:
# abc_151_d_Maze Master
import sys
from io import StringIO
import unittest
import os
from collections import deque

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    h, w = map(int, input().split())
    maze = [list(input()) for i in range(h)]

    # 作成したが、この処理はいらんかった・・(処理量は多くないので不要だった)
    start_list = []
    for i_len, i in enumerate(range(h)):
        for j_len, j in enumerate(range(w)):
            start_list.append((i, j))

    ans = 0
    que = deque()
    for start in start_list:
        que.appendleft(start)
        ed_list = [[-1 for i in range(w)] for j in range(h)]
        ed_list[start[0]][start[1]] = 0

        # BFS開始
        while len(que) is not 0:
            now = que.pop()

            # 各方向に移動
            for i, j in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
                # 処理対象の座標
                target = [now[0] + i, now[1] + j]

                # 処理対象のチェック
                # 外なら何もしない
                if not 0 <= target[0] < h or not 0 <= target[1] < w:
                    continue

                # 距離が設定されているなら何もしない
                if ed_list[target[0]][target[1]] != -1:
                    continue

                # 壁なら何もしない
                if maze[target[0]][target[1]] == "#":
                    continue

                # 処理対象に対する処理
                # キューに追加(先頭に追加するのでappendleft())
                que.appendleft(target)
                # 距離を設定(現在の距離+1)
                ed_list[target[0]][target[1]] = ed_list[now[0]][now[1]] + 1
                ans = max(ans, ed_list[target[0]][target[1]])

    print(ans)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """3 5
...#.
.#.#.
.#..."""
        output = """10"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_1(self):
        test_input = """1 2
.."""
        output = """1"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()