Problem:


Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.



Sample input:
3 3
...
...
...


Sample output:
4

Submission status: Wrong Answer

Solution code:

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

H,W = map(int,input().split(' '))
MAP = [None]*H
for i in range(H):
    MAP[i] = list(input())

ANS = 0
for i in range(H):
    for j in range(W):
        st = MAP[i][j]
        if st=='.':
            MAX = [0]

            cnt_MAP = [None]*H

            for m in range(H):
                cnt_MAP[m] = [-1 for _ in range(W)]

            #print('##',i,j)
            def dfs(h,w,cnt):
                #print(h,w,cnt_MAP)
                if (not (0<=h<H)) or (not (0<=w<W)):
                    return
                if MAP[h][w]=='#':
                    return

                cnt += 1
                if cnt_MAP[h][w]==-1 or cnt_MAP[h][w]>=cnt:
                    cnt_MAP[h][w] = cnt
                else:
                    return

                dfs(h+1,w,cnt)
                dfs(h-1,w,cnt)
                dfs(h,w+1,cnt)
                dfs(h,w-1,cnt)
            dfs(i,j,-1)
            tmp = 0
            for i in range(H):
                tmp = max(tmp,max(cnt_MAP[i]))
            ANS = max(ANS,tmp)

print(ANS)

Submission status: Wrong Answer

Solution code:
from collections import deque

def a():
    H,W = map(int,input().split())
    S = ["" for _ in range(H)]
    for _ in range(H):
        S[_] = input()
    b = lambda n:S[n//W][n%W] == '.'
    u = map(lambda n:(n%W,n//W),filter(b,range(H*W)))

    def bfs(root):
        depth = [[-1]*W for _ in range(H)]
        q = deque()
        q.append((root,0))
        while q:
            r,d = q.popleft()
            x,y = r
            depth[y][x] = d
            for dx,dy in ((1,0),(-1,0),(0,1),(0,-1)):
                dx += x
                dy += y
                if 0 <= dx < W and 0 <= dy < H and depth[dy][dx] == -1 and S[dy][dx] == ".":
                    q.append(((dx,dy),d+1))
        return depth

    print(max(map(max,map(max,map(bfs,u)))))





a()

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
MAP=[0]*H
for i in range(H):
    MAP[i]=list(input())

def calc(x,y):
    CMAP=[[0 for i in range(W)]for i in range(H)]
    LIST=[0 for i in range (3)]*10**4
    t=1
    k=0
    c=0
    LIST[0]=[x,y,c]
    while(True):
        x=LIST[k][0]
        y=LIST[k][1]
        c=LIST[k][2]
        if(x>0):
            if(CMAP[y][x-1]==0 and MAP[y][x-1]=="."):
                CMAP[y][x-1]=1
                LIST[t]=[x-1,y,c+1]
                t+=1
        if(y>0):
            if(CMAP[y-1][x]==0 and MAP[y-1][x]=="."):
                CMAP[y-1][x]=1
                LIST[t]=[x,y-1,c+1]
                t+=1
        if(x<W-1):
            if(CMAP[y][x+1]==0 and MAP[y][x+1]=="."):
                CMAP[y][x+1]=1
                LIST[t]=[x+1,y,c+1]
                t+=1
        if(y<H-1):    
            if(CMAP[y+1][x]==0 and MAP[y+1][x]=="."):
                CMAP[y+1][x]=1
                LIST[t]=[x,y+1,c+1]
                t+=1
        k+=1
        if(k==t):break
    return c

m=0
for i in range(H):
    for j in range(W):
        if MAP[i][j]=="." :
            m=max(m,calc(j,i))

print(m)

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = [int(v) for v in input().split()]

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


def find(maze):
    for i in range(h):
        for j in range(w):
            if maze[i][j] == '.':
                return (i, j)
    return None

def contains(maze, closed, i, j):
    if i < 0 or i >= h:
        return False
    if j < 0 or j >= w:
        return False
    key = (i, j)
    if key in closed:
        return False
    closed.add(key)

    return True

def far(maze, p):
    q = deque([])

    i0 = p[0]
    j0 = p[1]
    q.append((i0, j0, 0))

    closed = set()
    closed.add((i0, j0))
    max_dist = 0
    max_p = None
    while len(q) > 0:
        e = q.popleft()
        
        i = e[0]
        j = e[1]
        cost = e[2] + 1
        for n in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            ni = i + n[0]
            nj = j + n[1]
            nkey = (ni, nj)
            if not contains(maze, closed, ni, nj):
                continue
            if maze[ni][nj] != '.':
                continue
            q.append((ni, nj, cost))
            if max_dist < cost:
                max_dist = cost
                max_p = nkey
    return max_p, max_dist
    

p0 = find(maze)
p1, _  = far(maze, p0)
p2, max_dist = far(maze, p1)

print(max_dist)

Submission status: Wrong Answer

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

s = []
for i in range(h):
    line = input()
    s.append(line)

ans = []
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        d = [[1<<10 for x in range(w)] for y in range(h)]

        stack = []
        stack.append((i, j))
        d[i][j] = 0
        ma = 0
        while stack:
            y, x = stack.pop()
            if y > 0 and s[y-1][x] == '.' and d[y-1][x] > d[y][x]+1:
                d[y-1][x] = d[y][x] + 1
                stack.append((y-1, x))
            if x < w-1 and s[y][x+1] == '.' and d[y][x+1] > d[y][x]+1:
                d[y][x+1] = d[y][x] + 1
                stack.append((y, x+1))
            if y < h-1 and s[y+1][x] == '.' and d[y+1][x] > d[y][x]+1:
                d[y+1][x] = d[y][x] + 1
                stack.append((y+1, x))
            if x > 0 and s[y][x-1] == '.' and d[y][x-1] > d[y][x]+1:
                d[y][x-1] = d[y][x] + 1
                stack.append((y, x-1))
            if d[y][x] > ma:
                ma = d[y][x]
        ans.append(ma)
ans.sort()
print(ans[-1])

Submission status: Wrong Answer

Solution code:
import numpy as np
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
reach = [[False] * W for i in range(H)]
step = np.ones((H, W)) * (-1)
m = 0
q = queue.Queue()

for sh in range(H):
    for sw in range(W):
        if False and S[sh][sw] == '#':
            pass
        elif (sh - 1 >= 0 and S[sh -1][sw] != '#') and  (sh + 1 < H and S[sh +1][sw] != '#'):
            pass
        elif (sw - 1 >= 0 and S[sh][sw-1] != '#') and  (sw + 1 < W and S[sh][sw + 1] != '#'):
            pass
        else:
            reach = [[False] * W for i in range(H)]
            step = np.ones((H, W)) * (-1)
            q.put((sw, sh, 0))
            while not q.empty():
                x, y, s = q.get()
                if x < 0 or W <= x or y < 0 or H <= y:
                    pass
                elif reach[y][x]:
                    pass
                elif S[y][x] == '#':
                    pass
                else:
                    reach[y][x] = True
                    step[y, x] = min(s, step[y, x]) if step[y, x] != -1 else s

                    q.put((x+1, y, s+1))
                    q.put((x-1, y, s+1))
                    q.put((x, y-1, s+1))
                    q.put((x, y+1, s+1))

            m = max(m, np.max(step))

print(int(m))

Submission status: Wrong Answer

Solution code:
import heapq
import numpy as np

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

for i in range(H):
    for j, way in enumerate(input()):
        if way == '.':
            maze[i, j] = 1
        else:
            maze[i, j] = 0

able_list = []

for i in range(H):
    for j in range(W):
        able = []
        if maze[i,j] == 1:
            if 0 <= i-1 < H:
                if maze[i-1, j] == 1:
                    able.append([(i-1) * W + j, 1])
            if 0 <= j-1 < W:
                if maze[i, j-1] == 1:
                    able.append([i * W + j - 1, 1])
            if 0 <= j+1 < W:
                if maze[i, j+1] == 1:
                    able.append([i* W + j + 1, 1])
            if 0 <= i+1 < H:
                if maze[i+1, j] == 1:
                    able.append([(i+1)*W + j, 1])
        able_list.append(able)



def Dijkstra(list_adjlist, initnode):
    # list_Dを初期化
    list_D = [-1] * len(list_adjlist)
    # 始点の距離=0
    list_D[initnode] = 0
    # list_Tを初期化
    list_T = [-1] * len(list_adjlist)
    # 最短経路・距離が確定している点のリスト
    list_check = [False] * len(list_adjlist)
    # ヒープの初期化：暫定最短距離と点の名前をペアにしたリストをヒープに格納する
    list_S = []
    heapq.heappush(list_S, (list_D[initnode], initnode))
    # ヒープが空になるまで続ける
    while(len(list_S)):
        # ヒープから暫定最短距離が小さい点を取り出す
        pair_w_node = heapq.heappop(list_S)
        if list_check[pair_w_node[1]] is False:
            list_check[pair_w_node[1]] = True
            # 点pair_w_node[1]の各隣接点について調べる
            for neighbor in list_adjlist[pair_w_node[1]]:
                if list_D[neighbor[0]] == -1 or list_D[neighbor[0]] > list_D[pair_w_node[1]] + neighbor[1]:
                    list_D[neighbor[0]] = list_D[pair_w_node[1]] + neighbor[1]
                    list_T[neighbor[0]] = pair_w_node[1]
                    heapq.heappush(list_S, (list_D[neighbor[0]], neighbor[0]))
    return list_D, list_T

ans = 0
for i in range(H):
    for j in range(W):
        if maze[i, j] == 1:
            list_D, list_T = Dijkstra(able_list, i*W + j)
            if ans < max(list_D):
                ans = max(list_D)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
grid = []
for i in range(h):
    grid.append(list(input()))
def check(s,t):
    if (0 <= s <= w - 1) and (0 <= t <= h - 1):
        return True
    else:
        return False
def bfs(x, y, cost):
    if check(x,y):
        if grid[y][x] != "#":
            if cost < graph[y][x]:
                graph[y][x] = cost
                bfs(x+1,y,cost+1)
                bfs(x,y+1,cost+1)
                bfs(x-1,y,cost+1)
                bfs(x,y-1,cost+1)
ans = 0
inf = 70
for i in range(h):
    for j in range(w):
        graph = [[inf for _ in range(w)] for _ in range(h)]
        bfs(j,i,0)
        for p in range(h):
            for q in range(w):
                if graph[p][q] < inf:
                    ans = max(ans, graph[p][q])
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    H, W = [int(s) for s in input().split()]
    MAP = []
    for h in range(H):
        row = input()
        MAP.append(list(row))

    points = []
    for h in range(H):
        for w in range(W):
            if MAP[h][w] == '.':
                points.append((h, w))

    max_step = 0
    max_way = []
    for start_i in range(len(points) - 1):
        for goal_i in range(start_i + 1, len(points)):
            if points[start_i] in max_way or points[goal_i] in max_way:
                continue
            step, way = count_step(MAP, points[start_i], points[goal_i])
            if step > max_step:
                max_step = step
                max_way = way

    print(max_step)


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


def count_step(MAP, start, goal):
    candidates = [(start, get_distance(start, goal), 0, [start])]

    checked = {}
    while True:
        pos, _, step, way = candidates.pop(0)
        for m in MOVES:
            next_pos = (pos[0] + m[0], pos[1] + m[1])
            if next_pos in checked:
                continue
            if not is_valid(MAP, next_pos):
                continue
            checked[next_pos] = True
            new_way = list(way)
            new_way.append(next_pos)
            distance = get_distance(next_pos, goal)
            if distance == 0:
                return step + 1, new_way
            candidates.append((next_pos, distance, step + 1, new_way))
        candidates.sort(key=lambda x: x[1] + x[2])


def get_distance(p, goal):
    return abs(p[0] - goal[0]) + abs(p[1] - goal[1])


def is_valid(MAP, pos):
    if pos[0] < 0 or pos[1] < 0:
        return False
    if pos[0] >= len(MAP) or pos[1] >= len(MAP[0]):
        return False

    if MAP[pos[0]][pos[1]] == '#':
        return False
    return True


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
grid = []
for i in range(h):
    grid.append(list(input()))
def check(s,t):
    if (0 <= s <= w - 1) and (0 <= t <= h - 1):
        return True
    else:
        return False
def bfs(x, y, cost):
    if check(x,y):
        if grid[y][x] != "#":
            if cost < graph[y][x]:
                graph[y][x] = cost
                bfs(x+1,y,cost+1)
                bfs(x,y+1,cost+1)
                bfs(x-1,y,cost+1)
                bfs(x,y-1,cost+1)
ans = 1
inf = 70
for i in range(h):
    for j in range(w):
        graph = [[inf for _ in range(w)] for _ in range(h)]
        bfs(j,i,0)
        for p in range(h):
            for q in range(w):
                if graph[p][q] < inf:
                    ans = max(ans, graph[p][q])
print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
import numpy as np
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
reach = [[False] * W for i in range(H)]
step = np.ones((H, W)) * (-1)
m = 0
q = queue.Queue()

for sh in range(H):
    for sw in range(W):
        if S[sh][sw] == '#':
            pass
        elif (sh - 1 >= 0 and S[sh -1][sw] != '#') and  (sh + 1 < H and S[sh +1][sw] != '#'):
            pass
        elif (sw - 1 >= 0 and S[sh][sw-1] != '#') and  (sw + 1 < W and S[sh][sw + 1] != '#'):
            pass
        else:
            reach = [[False] * W for i in range(H)]
            step = np.ones((H, W)) * (-1)
            q.put((sw, sh, 0))
            while not q.empty():
                x, y, s = q.get()
                if x < 0 or W <= x or y < 0 or H <= y:
                    pass
                elif reach[y][x]:
                    pass
                elif S[y][x] == '#':
                    pass
                else:
                    reach[y][x] = True
                    step[y, x] = min(s, step[y, x]) if step[y, x] != -1 else s

                    q.put((x+1, y, s+1))
                    q.put((x-1, y, s+1))
                    q.put((x, y-1, s+1))
                    q.put((x, y+1, s+1))

            m = max(m, np.max(step))

print(int(m))

Submission status: Wrong Answer

Solution code:
def bfs(H, W, h, w, maze):
    if maze[h][w] == '#':
        return 0
    visited = []
    distance = []
    for i in range(H):
        visited.append([False] * W)
        distance.append([0] * W)
    position = [[h, w]]
    current = 0
    while len(position) > 0:
        h, w = iter(position.pop(0))
        current = distance[h][w]
        if h - 1 >= 0 and maze[h-1][w] == '.' and not(visited[h-1][w]):
            distance[h-1][w] = current + 1
            visited[h-1][w] = True
            position.append([h-1, w])
        if h + 1 < H and maze[h+1][w] == '.' and not(visited[h+1][w]):
            distance[h+1][w] = current + 1
            visited[h+1][w] = True
            position.append([h+1, w])
        if w - 1 >= 0 and maze[h][w-1] == '.' and not(visited[h][w-1]):
            distance[h][w-1] = current + 1
            visited[h][w-1] = True
            position.append([h, w-1])
        if w + 1 < W and maze[h][w+1] == '.' and not(visited[h][w+1]):
            distance[h][w+1] = current + 1
            visited[h][w+1] = True
            position.append([h, w+1])
    return current


H, W = map(int, input().split())
maze = []
for i in range(H):
    maze.append(input())
M = 0
for h in range(H):
    for w in range(W):
        d = bfs(H, W, h, w, maze)
        if d > M:
            M = d
print(M)

Submission status: Wrong Answer

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

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

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):
    global ans
    cs = copy.deepcopy(s)
    queueX = queue.Queue()
    queueY = queue.Queue()
    queueX.put(s1)
    queueY.put(s2)
    cs[s1][s2] = 0
    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
                ans = max(ans, cs[nextX][nextY])
                queueX.put(nextX)
                queueY.put(nextY)

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 range(H):
    for j in range(W):
        if s[i][j] == '.':
            bfs(i, j)
            break

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

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

ans = 0

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


def bfs(x, y):
    m = []
    for _ in range(H):
        m.append([-1] * W)

    q = deque()
    q.append([y, x, 0])
    maximus = 0

    while q:
        j, i, v = q.popleft()
        m[j][i] = v
        for dd in d:
            dj = j + dd[0]
            di = i + dd[1]
            if 0 <= dj < H and 0 <= di < W and m[dj][di] == -1 and S[dj][di] == ".":
                q.append([dj, di, v+1])
                if maximus < v+1:
                    maximus = v+1

    return maximus


for j in range(H):
    if W == 1:
        for i in range(W):
            if S[j][i] != ".":
                continue
            ans = max(ans, bfs(i, j))
    else:
        if j % 2 == 0:
            for i in range(0, W, 2):
                if S[j][i] != ".":
                    continue
                ans = max(ans, bfs(i, j))
        else:
            for i in range(1, W, 2):
                if S[j][i] != ".":
                    continue
                ans = max(ans, bfs(i, j))

if ans == 0:
    for j in range(H):
        for i in range(W):
            if S[j][i] == ".":
                print(1)
                sys.exit(0)

print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
MAP=[0]*H
for i in range(H):
    MAP[i]=list(input())

def calc(x,y):
    CMAP=[[0 for i in range(W)]for i in range(H)]
    LIST=[0 for i in range (3)]*10**4
    t=1
    k=0
    c=0
    LIST[0]=[x,y,c]
    while(True):
        if(k==t):break
        x=LIST[k][0]
        y=LIST[k][1]
        c=LIST[k][2]
        if(x>0):
            if(CMAP[y][x-1]==0 and MAP[y][x-1]=="."):
                CMAP[y][x-1]=1
                LIST[t]=[x-1,y,c+1]
                t+=1
        if(y>0):
            if(CMAP[y-1][x]==0 and MAP[y-1][x]=="."):
                CMAP[y-1][x]=1
                LIST[t]=[x,y-1,c+1]
                t+=1
        if(x<W-1):
            if(CMAP[y][x+1]==0 and MAP[y][x+1]=="."):
                CMAP[y][x+1]=1
                LIST[t]=[x+1,y,c+1]
                t+=1
        if(y<H-1):    
            if(CMAP[y+1][x]==0 and MAP[y+1][x]=="."):
                CMAP[y+1][x]=1
                LIST[t]=[x,y+1,c+1]
                t+=1
        k+=1
    return LIST[k-1][2]

m=0
for i in range(H):
    for j in range(W):
        if MAP[i][j]=="." :
            m=max(m,calc(j,i))

print(m)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

LOAD = '.'
WALL = '#'
NOT_REACHED = -1

h, w = [int(i) for i in input().split()]

s = [0] * h
for i in range(h):
    s[i] = input().strip()

def bfs(graph, queue, div):
    _max = 0
    while queue:
        current = queue.pop(0)

        top = (current[0] - 1, current[1])
        bottom = (current[0] + 1, current[1])
        left = (current[0], current[1] - 1)
        right = (current[0], current[1] + 1)

        for target in (top, bottom, left, right):
            if (target[0] < 0) or (target[0] >= h) or (target[1] < 0) or (target[1] >= w):
                continue
            if div[target] != NOT_REACHED:
                continue
            if graph[target[0]][target[1]] == LOAD:
                div[target] = div[current] + 1
                _max = max(div[target], _max)
                queue.append(target)
    return _max

ans = 0
for i in range(h):
    for j in range(w):
        queue = [(i, j)]
        div = {}
        for inner_i in range(h):
            for inner_j in range(w):
                div[(inner_i, inner_j)] = NOT_REACHED
        div[(i, j)] = 0
        ans = max(bfs(s, queue, div), ans)

print(ans)

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
meiro = [list(input()) for i in range(h)]
max_d = 0
from collections import deque

def bfs(sx,sy):
    que = deque([(sx,sy,0)])
    d = [[0]*w for i in range(h)]
    d[sx][sy] = 1
    max_len=0
    while que:
        x,y,tmp_len =que.popleft()
        for dx,dy in [(0,1),(1,0),(-1,0),(0,-1)]:
            tmp = tmp_len
            nx,ny = x+dx,y+dy
            if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0 and meiro[nx][ny] =='.':
                d[nx][ny] = 1
                tmp+=1
                max_len = max(max_len, tmp)
                que.append((nx,ny,tmp))
    return max_len

for s_i in range(h):
    for s_j in range(w):
        max_d = max(bfs(s_i,s_j), max_d)
print(max_d)

Submission status: Wrong Answer

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


"""
s_idx = [-1,-1]
g_idx = [-1,-1]

for i in range(h):
    for j in range(w):
        if s[i][j] == 'S':
            s_idx[0] = i
            s_idx[1] = j
        if s[i][j] == 'G':
            g_idx[0] = i
            g_idx[1] = j
"""

tate = [0,0,1,-1]
yoko = [-1,1,0,0]

mat=[[10**18 for i in range(w*h)] for j in range(w*h)]

for i in range(w*h):
    if s[i//w][i%w] == '#':
        mat[i][i] = 10**18
        
    mat[i][i] = 0

for i in range(w*h):
    for j in range(4):
        next_idx = i + w*tate[j] + yoko[j]
        if next_idx < 0 or next_idx >= w*h:
            continue
        if i % w == 0:
            if j == 0:
                continue
        if i % w == w - 1:
            if j == 1:
                continue
        if s[next_idx//w][next_idx%w] == '#':
            mat[i][next_idx] = 10**18
        else:
            mat[i][next_idx] = 1

for i in range(w*h):
    #print(i,i,i,i,i,i,i,i,i)
    for x in range(w*h):
        for y in range(w*h):
            """
            if x == s_idx[0]*w+s_idx[1] and y == g_idx[0]*w+g_idx[1]:
                print(mat[x][y],mat[x][i] , mat[i][y],i)
            """
            mat[x][y] = min(mat[x][y], mat[x][i] + mat[i][y])
    
ans = h*w
tmp = []

for i in range(w*h):
    for j in range(w*h):
        if ans > mat[i][j]:
            tmp.append(mat[i][j])
            
print(max(tmp))

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
meiro = [list(input()) for i in range(h)]
max_d = 0
from collections import deque

def bfs(sx,sy):
    que = deque([(sx,sy,0)])
    d = [[0]*w for i in range(h)]
    d[sx][sy] = 1
    max_len=0
    while que:
        x,y,tmp_len =que.popleft()
        for dx,dy in [(0,1),(1,0),(-1,0),(0,-1)]:
            nx,ny = x+dx,y+dy
            if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0 and meiro[nx][ny] =='.':
                d[nx][ny] = 1
                tmp_len+=1
                max_len = max(max_len, tmp_len)
                que.append((nx,ny,tmp_len))
    return max_len

for s_i in range(h):
    for s_j in range(w):
        max_d = max(bfs(s_i,s_j), max_d)
print(max_d)

Submission status: Wrong Answer

Solution code:
import queue
import copy
 
def ngoin(bo,now):
    return 0 <= now[0] and now[0] < len(bo) and 0 <= now[1] and now[1] < len(bo[0])
 
def minido(bo,si,sj):
    tb = [[False for i in range(len(bo[0]))] for j in range(len(bo))]
    q = queue.Queue()
    q.put([si,sj,0])
    tb[si][sj] = True
    ret = 0
    while not q.empty():
        now = q.get()
        ret = now[2]
        if ngoin(bo,[now[0]-1,now[1]]):
            if bo[now[0]-1][now[1]] and not tb[now[0]-1][now[1]]:
                q.put([now[0]-1,now[1],now[2]+1])
                tb[now[0]][now[1]] = True
                
        if ngoin(bo,[now[0],now[1]+1]):
            if bo[now[0]][now[1]+1] and not tb[now[0]][now[1]+1]:
                q.put([now[0],now[1]+1,now[2]+1])
                tb[now[0]][now[1]+1] = True
                
        if ngoin(bo,[now[0]+1,now[1]]):
            if bo[now[0]+1][now[1]] and not tb[now[0]+1][now[1]]:
                q.put([now[0]+1,now[1],now[2]+1])
                tb[now[0]+1][now[1]] = True
                
        if ngoin(bo,[now[0],now[1]-1]):
            if bo[now[0]][now[1]-1] and not tb[now[0]][now[1]-1]:
                q.put([now[0],now[1]-1,now[2]+1])
                tb[now[0]][now[1]-1] = True
    return ret
            
 
h,w = map(int,input().split())
bo = [[True if x == '.' else False for x in input()] for i in range(h)]
grap = [[float('inf') for i in range(h*w)] for j in range(h*w)]
ans = 0
for i in range(h*w):
    grap[i][i] = 0
for si in range(h):
    for sj in range(w):
        if not bo[si][sj]:
            continue
        ans = max(ans,minido(bo,si,sj))
                
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import itertools
import copy
import numpy as np

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

def solve(S, s):
    M = copy.deepcopy(S)
    d = [[1, 0], [-1, 0], [0, -1], [0, 1]]
    queue = deque([s])
    steps = [[-1 for _ in range(W)] for _ in range(H)]
    # steps = [[np.max for _ in range(W)] for _ in range(H)]
    # steps = [[H*W+1 for _ in range(W)] for _ in range(H)]
    steps[s[0]][s[1]] = 0

    while len(queue) > 0:
        current = queue.popleft()
        cy = current[0]
        cx = current[1]
        # if cy == g[0] and cx == g[1]:
        #     return steps[cy][cx]
        # else:
        M[cy][cx] = '#'
        for i in d:
            next = [cy+i[0], cx+i[1]]
            # はみ出さないかつ通ってない
            if (0<=next[0]<H and 0<=next[1]<W) and M[next[0]][next[1]]!='#':
                queue.append(next)
                steps[next[0]][next[1]] = steps[cy][cx] + 1
    print(steps)
    # [i. for i in steps]
    # print(steps)
        
    return max([max(i) for i in steps])
# print(solve(S, [0, 0], [0, 1]))
# print(solve(S, [2, 0], [0, 4]))
# print(S)
maxStep = 0
for s in itertools.product(range(H), range(W)):
    if S[s[0]][s[1]] == '.':
        # print(s, g)
        # print(solve(S, [s[0], s[1]], [g[0], g[1]]))
        maxStep = max(solve(S, [s[0], s[1]]), maxStep)

print(maxStep)