#34199: python解


s116113@elvs.chc.edu.tw (資處甲116113許銪升)

學校 : 國立二林高級工商職業學校
編號 : 213088
來源 : [118.232.28.227]
最後登入時間 :
2024-01-07 20:21:31
a597. 祖靈被榨乾了!!!!!!!! -- 成為祖靈的祖靈 | From: [118.232.28.25] | 發表日期 : 2023-03-05 19:39

from collections import deque

# 定義BFS函數,用來搜索JIZZ的攤數和最大攤的面積
def bfs(grid, i, j):
    # 設置四個方向
    dirs = [(0,1),(1,0),(-1,0),(0,-1)]
    # 計算JIZZ的攤數和最大攤的面積
    count, max_area = 0, 0
    # 創建一個雙向隊列,從初始點開始
    queue = deque([(i, j)])
    # 設置初始點已被訪問
    grid[i][j] = 'X'
    # 進入BFS
    while queue:
        # 從隊列中取出一個節點
        r, c = queue.popleft()
        # 更新攤數和最大攤的面積
        count += 1
        max_area = max(max_area, count)
        # 探索四個方向
        for dr, dc in dirs:
            nr, nc = r + dr, c + dc
            # 如果下一個點在網格中,並且是JIZZ,則將其添加到隊列中並標記為已訪問
            if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 'J':
                queue.append((nr, nc))
                grid[nr][nc] = 'X'
    return count, max_area

# 讀入總共有多少組測試數據
num_cases = int(input())

依次處理每個測試數據
for _ in range(num_cases):
    # 讀入網格的大小
    m, n = map(int, input().split())
    # 創建一個網格
    grid = []
    for i in range(m):
        row = input().strip()
        grid.append(list(row))
    # 遍歷網格,找到第一個JIZZ,進行BFS
    count, max_area = 0, 0
    for i in range(m):
        for j in range(n):
            if grid[i][j] == 'J':
                c, a = bfs(grid, i, j)
                count += 1
                max_area = max(max_area, a)
    # 輸出結果
    print(count, max_area)

不使用套件的話會導致時間複雜度從O(1)變為O(n),從而導致程序變慢

def bfs(x, y):
    queue = [(x, y)]
    visited[x][y] = True
    area = 0
    while queue:
        area += 1
        i, j = queue.pop(0)
        for di, dj in directions:
            ni, nj = i + di, j + dj
            if ni < 0 or ni >= m or nj < 0 or nj >= n:
                continue
            if visited[ni][nj] or not room[ni][nj]:
                continue
            visited[ni][nj] = True
            queue.append((ni, nj))

    return area


m, n = map(int, input().split())
room = []
for i in range(m):
    row = input().strip()
    room.append([c == 'J' for c in row])
visited = [[False] * n for _ in range(m)]
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

num_areas = 0
max_area = 0
for i in range(m):
    for j in range(n):
        if not visited[i][j] and room[i][j]:
            num_areas += 1
            area = bfs(i, j)
            max_area = max(max_area, area)

print(num_areas, max_area)

 
ZeroJudge Forum