From 6cba2883a41060620a3ac53149a7d9c7557f9d5a Mon Sep 17 00:00:00 2001 From: Azureki Date: Thu, 11 Oct 2018 22:14:33 +0800 Subject: [PATCH] =?UTF-8?q?BFS=E8=A7=A3=E6=B3=95=20732ms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lc200. Number of Islands.py | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 lc200. Number of Islands.py diff --git a/lc200. Number of Islands.py b/lc200. Number of Islands.py new file mode 100644 index 0000000..a208e51 --- /dev/null +++ b/lc200. Number of Islands.py @@ -0,0 +1,47 @@ +import queue + + +class Solution: + def numIslands(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + if not grid: + return 0 + res = 0 + length = len(grid) + length0 = len(grid[0]) + + q = queue.Queue() + visited = [[0] * length0 for i in range(length)] + + for i in range(length): + for j in range(length0): + if not visited[i][j] and grid[i][j] == '1': + q.put((i, j)) + res += 1 + while not q.empty(): + + isl = q.get() + if isl[0] < 0 or isl[0] >= length: + continue + if isl[1] < 0 or isl[1] >= length0: + continue + if not visited[isl[0]][isl[1]] and grid[isl[0]][isl[1]] == '1': + visited[isl[0]][isl[1]] = 1 + q.put((isl[0] - 1, isl[1])) + q.put((isl[0] + 1, isl[1])) + q.put((isl[0], isl[1] - 1)) + q.put((isl[0], isl[1] + 1)) + return res + + +snum = '''11000 +11000 +00100 +00011''' +slst = snum.split('\n') +grid = [[int(x) for x in list(s)] for s in slst] +soln = Solution() +print(soln.numIslands(slst))