[每日CPE] UVA10336

作者: kerycheng (kk)   2022-12-19 16:14:35
UVA10336 Rank the Languages
經典的DFS油田題目,這題只需要分上下左右,不需要計算斜向
大意就是會給你一張由英文字母組成的地圖
要你計算所出現的英文字母"區塊"的次數,例如
ttuuttdd
ttuuttdd
uuttuudd
uuttuudd
這樣t有三塊、u有三塊、d只有一塊
input的第一行會告訴你有幾筆測資,第二行是地圖的高和寬,第三行開始就是地圖
output規定輸出是world #n,n代表第幾筆測資。接下來就是把出現的字母按照出現次數由
大到小印出來,如果次數相同則從較小的字母開始印
程式:
def dfs(_map, ifvisited, i, j):
# 將當前位置記錄已訪問
ifvisited[i][j] = True
if _map[i + 1][j] == _map[i][j] and not ifvisited[i + 1][j]:
dfs(_map, ifvisited, i + 1, j)
if _map[i][j + 1] == _map[i][j] and not ifvisited[i][j + 1]:
dfs(_map, ifvisited, i, j + 1)
if _map[i - 1][j] == _map[i][j] and not ifvisited[i - 1][j]:
dfs(_map, ifvisited, i - 1, j)
if _map[i][j - 1] == _map[i][j] and not ifvisited[i][j - 1]:
dfs(_map, ifvisited, i, j - 1)
# 讀計算次數
N = int(input())
for i in range(N):
# 讀高、寬
H, W = map(int, input().split())
count = [0] * 26 # 存出現的英文字母
max_ = -1 # 紀錄最大的區塊數
world_map = [] # 存地圖
ifvisited = [] # 記錄訪問過的位置
# 讀地圖並在上下兩行新增空格
world_map.append(' ' * (W + 2))
for j in range(H):
input_ = input()
world_map.append(' ' + input_ + ' ')
world_map.append(' ' * (W + 2))
ifvisited = [[False] * (W + 2) for _ in range(H + 2)]
# 遍歷地圖每個位置
for j in range(1, H + 1):
for k in range(1, W + 1):
# 如果當前位置沒被訪問 就進行DFS
if not ifvisited[j][k]:
# 更新最大值
if max_ < count[ord(world_map[j][k]) - ord('a')] + 1:
max_ = count[ord(world_map[j][k]) - ord('a')] + 1
# 進行DFS 並讓字母++
dfs(world_map, ifvisited, j, k)
count[ord(world_map[j][k]) - ord('a')] += 1
print("World #{}".format(i + 1))
for j in range(max_, 0, -1):
for k in range(26):
if count[k] == j:
print("{}: {}".format(chr(k + ord('a')), count[k]))
作者: wu10200512 (廷廷)   2022-12-19 16:15:00
大師
作者: JenniferLope (ㄚ)   2022-12-19 16:19:00
大師
作者: ILoveErr (英梨梨我老婆)   2022-12-19 16:25:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com