directions = [(1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)] class Solution: def __init__(self, row, col): self.flag_arr = [[0 for i in range(col)] for j in range(row)] self.stack = [] self.stack_num = 0 self.max = 0 self.min = 100000 self.mid = 0 def bianli(self, arr, rows, cols): #广度优先遍历 for i in range(rows): for j in range(cols): if self.flag_arr[i][j] == 0 and arr[i][j] != 0: self.stack.append((i, j)) print((i, j)) self.stack_num += 1 self.mid += arr[i][j] self.flag_arr[i][j] = 1 while self.stack_num: local_x, local_y = self.stack.pop() self.stack_num -= 1 for dir_x, dir_y in directions: if 0 <= local_x + dir_x < rows \ and 0 <= local_y + dir_y < cols \ and self.flag_arr[local_x + dir_x][local_y + dir_y] == 0 \ and arr[local_x + dir_x][local_y + dir_y] != 0: self.stack.append((local_x + dir_x, local_y + dir_y)) print((local_x + dir_x, local_y + dir_y)) self.stack_num += 1 self.mid += arr[local_x + dir_x][local_y + dir_y] self.flag_arr[local_x + dir_x][local_y + dir_y] = 1 if self.mid > self.max: self.max = self.mid if self.mid <= self.min and self.mid != 0: self.min = self.mid self.mid = 0 array = [ [1, 1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1], ] rows = 6 cols = 8 so = Solution(rows, cols) so.bianli(array, rows, cols) print(so.max) print(so.min) ''' if __name__ == "__main__": row = int(input("row:")) col = int(input("col:")) arr = [[0 for i in range(col)] for j in range(row)] #arr = [[0]*col]*row for i in range(row): string = input().strip().split() for j in range(col): arr[i][j] = string[j] so.bianli(array, rows, cols) print(so.max) print(so.min) '''
八阵图代码,目测可行
猜你喜欢
转载自blog.csdn.net/z2539329562/article/details/80288632
今日推荐
周排行