Python判斷海域有多少個小島

Miku丨無形發表於2021-01-02

在一片大海中 有很多小島
我們將小島所在的位置定義為1,海水的位置定義為0
小島如果上下左右相連線,那麼就是一個整體
我們要從中判斷 整片海域有多少個小島
[“1”,“1”,“1”,“1”,“0”],

[“1”,“1”,“0”,“1”,“0”],

[“1”,“1”,“0”,“0”,“0”],

[“0”,“0”,“0”,“0”,“0”]
這就是一片海域
可以看出裡面只有一個島嶼
我們寫程式來識別一下

首先 我們讀取所有島嶼的座標 將小島篩選出來

# 資料座標儲存列表
data_1 = []
# 將座標新增到列表中
for i in range(len(grid)):
    for j in range(len(grid[i])):
        if int(grid[i][j]):
            data_1.append((i, j))

然後迴圈判斷同一島嶼的座標

# 臨時資料列表
data_2 = []
# 計算區域座標
while data_1:
    d = [data_1.pop()]
    # 處理處於同一區域的座標
    while True:
        for i in d:
            if (i[0] + 1, i[1]) in data_1:
                data_1.remove((i[0] + 1, i[1]))
                d.append((i[0] + 1, i[1]))
            if (i[0] - 1, i[1]) in data_1:
                data_1.remove((i[0] - 1, i[1]))
                d.append((i[0] - 1, i[1]))
            if (i[0], i[1] + 1) in data_1:
                data_1.remove((i[0], i[1] + 1))
                d.append((i[0], i[1] + 1))
            if (i[0], i[1] - 1) in data_1:
                data_1.remove((i[0], i[1] - 1))
                d.append((i[0], i[1] - 1))
        if (i[0] + 1, i[1]) not in data_1 or (i[0] - 1, i[1]) not in data_1 \
                or (i[0], i[1] + 1) not in data_1 or (i[0], i[1] - 1) not in data_1:
            break
    data_2.append(d)

完整程式碼如下:

# grid = [
#
#   ["1","1","0","0","0"],
#
#   ["1","1","0","0","0"],
#
#   ["0","0","1","0","0"],
#
#   ["0","0","0","1","1"]
#
# ]
grid = [

  ["1","1","1","1","0"],

  ["1","1","0","1","0"],

  ["1","1","0","0","0"],

  ["0","0","0","0","0"]

]
# 資料座標儲存列表
data_1 = []
# 將座標新增到列表中
for i in range(len(grid)):
    for j in range(len(grid[i])):
        if int(grid[i][j]):
            data_1.append((i, j))

# 臨時資料列表
data_2 = []
# 計算區域座標
while data_1:
    d = [data_1.pop()]
    # 處理處於同一區域的座標
    while True:
        for i in d:
            if (i[0] + 1, i[1]) in data_1:
                data_1.remove((i[0] + 1, i[1]))
                d.append((i[0] + 1, i[1]))
            if (i[0] - 1, i[1]) in data_1:
                data_1.remove((i[0] - 1, i[1]))
                d.append((i[0] - 1, i[1]))
            if (i[0], i[1] + 1) in data_1:
                data_1.remove((i[0], i[1] + 1))
                d.append((i[0], i[1] + 1))
            if (i[0], i[1] - 1) in data_1:
                data_1.remove((i[0], i[1] - 1))
                d.append((i[0], i[1] - 1))
        if (i[0] + 1, i[1]) not in data_1 or (i[0] - 1, i[1]) not in data_1 \
                or (i[0], i[1] + 1) not in data_1 or (i[0], i[1] - 1) not in data_1:
            break
    data_2.append(d)
print(len(data_2))

效果圖如下:
在這裡插入圖片描述
在這裡插入圖片描述
一起學習python,小白指導,教學分享記得私信我

相關文章