Crack LeetCode 之 200. Number of Islands
阿新 • • 發佈:2018-12-22
https://leetcode.com/problems/number-of-islands/
本題解法的巧妙之處在於,把含有1的島合併,這樣只要統計1的個數就能知道有多少個島。另外,本解法直接在傳入的gird中儲存合併結果,也節約了記憶體。以下為C++和python的程式碼,時間複雜度為O(m*n),空間複雜度為O(1)。
struct Solution { int numIslands(vector<vector<char>>& grid) { if(grid.empty() || grid[0].empty()) return 0; int count=0; int m = grid.size(); int n = grid[0].size(); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]=='1'){ count++; merge(grid, i, j); } } } return count; } void merge(vector<vector<char>>& grid, int i, int j){ int m=grid.size(); int n=grid[0].size(); if(i<0 || i>=m || j<0 || j>=n || grid[i][j]!='1') return; grid[i][j]='X'; merge(grid, i-1, j); merge(grid, i+1, j); merge(grid, i, j-1); merge(grid, i, j+1); } };
class Solution: def numIslands(self, grid): if grid == None or len(grid) == 0 or grid[0] == None: return 0 count = 0 m = len(grid) n = len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == '1': count = count + 1 self.merge( grid, i, j ) return count def merge(self, grid, i, j): if grid == None or grid[0] == None: return m = len(grid) n = len(grid[0]) if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != '1': return grid[i][j] = 'X' self.merge(grid, i-1, j) self.merge(grid, i+1, j) self.merge(grid, i, j-1) self.merge(grid, i, j+1)