BOJ:2667単番号、Python:strip-rstrip差異


番号のみ
import sys


def isVisitable(x, y):
    if x < 0 or x >= len_map or y < 0 or y >= len_map:
        return False
    if list_map[y][x] == 1:
        return True
    else:
        return False


def visitAll(x_pos, y_pos):
    global list_map
    visit_count = 1

    visit_list = [(x_pos, y_pos)]
    list_map[y_pos][x_pos] = 0

    x_list = [1, -1, 0, 0]
    y_list = [0, 0, 1, -1]

    while len(visit_list) != 0:
        a, b = visit_list.pop()
        for (x, y) in zip(x_list, y_list):
            new_x = a + x
            new_y = b + y
            if isVisitable(new_x, new_y):
                # print(new_x,new_y, "visitable")
                list_map[new_y][new_x] = 0
                visit_list.append((new_x, new_y))
                visit_count += 1
    return visit_count


len_map = int(sys.stdin.readline())

list_map = []

for _ in range(len_map):
    a = list(map(int, list(sys.stdin.readline().strip())))
    list_map.append(a)

answer = list()

for i in range(len_map):
    for j in range(len_map):
        if isVisitable(i, j):
            # print(i,j)
            visit_count = visitAll(i, j)
            answer.append(visit_count)

answer.sort()
print(len(answer))
for ans in answer:
    print(ans)
isVisitable(x,y):x,y位置の点有家はtrue,無家はfalseである.visitAll(x,y):所与のx,yに接続されたすべての場所を訪問し、家があるかどうかを確認し、訪問する場所をすべて0に設定する(家がないように).家屋の位置の数を返します.
以前解いたもの.

import sys
n = int(sys.stdin.readline())

houses = [list(map(int, list(sys.stdin.readline().rstrip()))) for i in range(n)]
answer = list()


def checkList(a, b):
    ans = list()
    if a > 0:
        ans.append([a - 1, b])
    if a < n - 1:
        ans.append([a + 1, b])
    if b > 0:
        ans.append([a, b - 1])
    if b < n - 1:
        ans.append([a, b + 1])
    return ans


def exist(x):
    a, b = x
    return True if houses[a][b] == 1 else 0


def check(list_, visited):
    a, b = list_
    visited.append([a, b])
    new_visit = []
    new_visit.append(list_)
    global houses
    for dot in checkList(a, b):
        if exist(dot) and dot not in visited:
            new_visit.extend(check(dot, visited))
    return new_visit


def delete(list_):
    global houses
    for dot in list_:
        x, y = dot
        houses[x][y] = 0


for i in range(n):
    for j in range(n):
        if exist([i, j]):
            x = check([i, j], [])
            answer.append(len(x))
            delete(x)

print(len(answer))
answer.sort()
for i in answer:
    print(i)
最近より長くかかりました.最近訪問した家を0に変更し、ここで訪問した家を訪問リストに保存して、訪問するかどうかを判断します.ここでは関数がもっと簡潔に書かれているようです.
Python:strip()、rstrip()差異strip():文字列の両端のスペースを削除rstrip():文字列の右側のスペースを削除lstrip():文字列の左側のスペースを削除