post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2598656/simple-python3-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if len(nums) == 0: return 0 max_len, cur_len = 0, 1 nums.sort() for i in range(1, len(nums)): if nums[i-1] == nums[i]-1: cur_len += 1 elif nums[i-1] < nums[i]-1: max_len = max(max_len, cur_len) cur_len = 1 return max(max_len, cur_len)
longest-consecutive-sequence
simple python3 solution
codeSheep_01
0
48
longest consecutive sequence
128
0.489
Medium
1,500
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2592483/Simple-Python-O(n)-Solution-or-Beats-99
class Solution: def longestConsecutive(self, nums: List[int]) -> int: ans = 0 s = set(nums) for i in s: if i - 1 not in s: curr = i c = 1 while curr + 1 in s: curr += 1 c += 1 ans = max(c, ans) return ans
longest-consecutive-sequence
Simple Python O(n) Solution | Beats 99%
kanchitank
0
68
longest consecutive sequence
128
0.489
Medium
1,501
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2571734/Python3-With-Set-or-Faster-Than-95
class Solution: def longestConsecutive(self, nums: List[int]) -> int: longest, s = 0, set(nums) for num in nums: if num in s: l = num - 1 while l in s: s.remove(l) l -= 1 r = num + 1 while r in s: s.remove(r) r += 1 longest = max(longest, r - l - 1) return longest
longest-consecutive-sequence
Python3 With Set | Faster Than 95%
ryangrayson
0
47
longest consecutive sequence
128
0.489
Medium
1,502
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2558082/Faster-than-99.36-Solutions
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 res = 0 n = set(nums) m = list(n) l = sorted(m) count = 1 for i in range(1,len(l)): if l[i]==(l[i-1]+1): count+=1 else: res = max(res,count) count = 1 res = max(res,count) return res
longest-consecutive-sequence
Faster than 99.36% Solutions
jayeshvarma
0
115
longest consecutive sequence
128
0.489
Medium
1,503
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2480393/Python-Sorting-Solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = sorted(nums) index = 0 maxLen = 0 while index < len(nums): l = 1 while index+1 < len(nums) and (nums[index+1]-nums[index] == 0 or nums[index+1]-nums[index] == 1): if nums[index+1]-nums[index] == 0: pass else: l += 1 index += 1 maxLen = max(l, maxLen) index += 1 return(maxLen)
longest-consecutive-sequence
Python Sorting Solution
DietCoke777
0
40
longest consecutive sequence
128
0.489
Medium
1,504
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2446418/Janky-Python-Solution-using-Dynamic-Programming
class Solution: def longestConsecutive(self, nums: List[int]) -> int: ilen = len(nums) if ilen < 1: return 0 elif ilen == 1: return 1 hash_map = dict() longest = 0 cache = dict() for num in nums: hash_map[num] = num + 1 for key in hash_map.keys(): chain = 0 temp = key while temp in hash_map: chain += 1 temp = hash_map[temp] if temp in cache: chain += cache[temp] break cache[key] = chain if chain > longest: longest = chain return longest
longest-consecutive-sequence
Janky Python Solution using Dynamic Programming
DavidLlanio
0
81
longest consecutive sequence
128
0.489
Medium
1,505
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2425862/Python-oror-Simple-and-Easy-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = set(nums) longest = 0 for num in nums: if num - 1 not in nums: curr = num while curr + 1 in nums: curr += 1 longest = max(longest, curr - num + 1) return longest
longest-consecutive-sequence
Python || Simple and Easy solution
Gyalecta
0
82
longest consecutive sequence
128
0.489
Medium
1,506
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2402503/python-simple-solution-O(nlogn)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if len(nums) == 0: return 0 nums.sort() count = 1 max_count = 1 for i in range(1,len(nums)): if nums[i]-1==nums[i-1]: count += 1 if max_count < count: max_count = count elif nums[i] != nums[i-1]: count = 1 return max_count
longest-consecutive-sequence
python simple solution O(nlogn)
AshishGohil
0
15
longest consecutive sequence
128
0.489
Medium
1,507
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2327609/Python-6872-test-passed-Time-complexity-O(n*k)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: lengthLong=0 prevMap = {} for i, n in enumerate(nums): prevMap[n]=i for i, n in enumerate(nums): count=1 while n+1 in prevMap: count+=1 n+=1 lengthLong=max(lengthLong,count) return lengthLong
longest-consecutive-sequence
Python 68/72 test passed Time complexity O(n*k)
Simon-Huang-1
0
9
longest consecutive sequence
128
0.489
Medium
1,508
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557540/Python-99-speed-99-memory
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def helper(node, num): if node is None: return 0 num = num * 10 + node.val if node.left is None and node.right is None: return num return helper(node.left, num) + helper(node.right, num) return helper(root, 0)
sum-root-to-leaf-numbers
Python 99% speed, 99% memory
dereky4
4
391
sum root to leaf numbers
129
0.588
Medium
1,509
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/703693/Python3-iterative-and-recursive-dfs
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: ans = 0 stack = [(root, 0)] while stack: node, val = stack.pop() val = 10*val + node.val if not node.left and not node.right: ans += val if node.left: stack.append((node.left, val)) if node.right: stack.append((node.right, val)) return ans
sum-root-to-leaf-numbers
[Python3] iterative & recursive dfs
ye15
2
68
sum root to leaf numbers
129
0.588
Medium
1,510
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/703693/Python3-iterative-and-recursive-dfs
class Solution: def sumNumbers(self, root: TreeNode) -> int: def fn(node, val): """Return sum of node-to-leaf numbers""" if not node: return 0 val = 10*val + node.val if not node.left and not node.right: return val return fn(node.left, val) + fn(node.right, val) return fn(root, 0)
sum-root-to-leaf-numbers
[Python3] iterative & recursive dfs
ye15
2
68
sum root to leaf numbers
129
0.588
Medium
1,511
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557634/Python-Easy-and-Clean-DFS-Solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: ans = 0 def dfs(node, num): if node.left: dfs(node.left, num*10 + node.left.val) if node.right: dfs(node.right, num*10 + node.right.val) if not node.left and not node.right: nonlocal ans ans += num dfs(root, root.val) return ans
sum-root-to-leaf-numbers
[Python] Easy & Clean DFS Solution
nomofika
1
105
sum root to leaf numbers
129
0.588
Medium
1,512
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1416739/Level-by-level-no-recursion-96-speed
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: if not root: return 0 ans = 0 row = [[root, []]] while row: new_row = [] for node, lst_val in row: if not node.left and not node.right: ans += int("".join(map(str, lst_val + [node.val]))) if node.left: new_row.append([node.left, lst_val + [node.val]]) if node.right: new_row.append([node.right, lst_val + [node.val]]) row = new_row return ans
sum-root-to-leaf-numbers
Level by level, no recursion, 96% speed
EvgenySH
1
165
sum root to leaf numbers
129
0.588
Medium
1,513
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/913856/Python-easy-recursive-dfs
class Solution: def sumNumbers(self, root: TreeNode) -> int: def solve(node, cur=0): if not node: return 0 if not node.left and not node.right: return cur * 10 + node.val return solve(node.left, cur*10 + node.val) + solve(node.right, cur * 10 + node.val) return solve(root)
sum-root-to-leaf-numbers
Python easy recursive dfs
modusV
1
108
sum root to leaf numbers
129
0.588
Medium
1,514
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2812117/python3-10-line-Sol.-faster-then-96.3
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def helper(root,ans): if root is None: return 0 ans=ans*10 + root.val if root.left is None and root.right is None: return ans return helper(root.left,ans) + helper(root.right,ans) return helper(root, 0)
sum-root-to-leaf-numbers
python3 10 line Sol. faster then 96.3%
pranjalmishra334
0
4
sum root to leaf numbers
129
0.588
Medium
1,515
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2806095/EASIEST-SIMPLE-PYTHON-RECUSRSION-WITH-COMMENTS
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: arr = self.helper(root,"",[]) print(arr) return sum(list(map(int,list(arr)))) def helper(self,root,string,arr): if(root is None): return "" # ON REACHING LEAF NODE if(root.left is None and root.right is None): arr.append(string+str(root.val)) self.helper(root.left,string+str(root.val),arr) self.helper(root.right,string+str(root.val),arr) return arr
sum-root-to-leaf-numbers
EASIEST SIMPLE PYTHON RECUSRSION WITH COMMENTS
MAYANK-M31
0
2
sum root to leaf numbers
129
0.588
Medium
1,516
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2803145/Python-(Faster-than-90)-or-DFS-solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: res = 0 def dfs(node, num): nonlocal res if node: num.append(str(node.val)) if not node.left and not node.right: res += int(''.join(num)) dfs(node.left, num) dfs(node.right, num) num.pop() dfs(root, []) return res
sum-root-to-leaf-numbers
Python (Faster than 90%) | DFS solution
KevinJM17
0
1
sum root to leaf numbers
129
0.588
Medium
1,517
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2659651/Python-3-7-liner-super-simple-and-easy-to-understand
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def dfs(node, curr_num): if node is None: return 0 curr_num += str(node.val) if node.left is None and node.right is None: return int(curr_num) return dfs(node.left, curr_num) + dfs(node.right, curr_num) return dfs(root, '')
sum-root-to-leaf-numbers
Python 3 7-liner, super simple and easy to understand
zakmatt
0
12
sum root to leaf numbers
129
0.588
Medium
1,518
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2639371/Python-DFS-Easy-Simple-5-line-code
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def dfs(root, num): if root is None: return 0 num = num * 10 + root.val if root.left is None and root.right is None: return num return dfs(root.left, num) + dfs(root.right, num) return dfs(root, 0)
sum-root-to-leaf-numbers
✔️ [Python] DFS Easy, Simple 5 line code
girraj_14581
0
9
sum root to leaf numbers
129
0.588
Medium
1,519
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2519954/Easy-Python-solution-BFS-(Beats-95)
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: if not root: return 0 q=deque() q.append([root,str(root.val)]) res=0 while q: node,sval=q.popleft() if not node.left and not node.right: res+=int(sval) if node.left: q.append([node.left,sval+str(node.left.val)]) if node.right: q.append([node.right,sval+str(node.right.val)]) return res
sum-root-to-leaf-numbers
Easy Python solution, BFS (Beats 95%)
shatheesh
0
25
sum root to leaf numbers
129
0.588
Medium
1,520
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2490970/python-easy-dfs-solution-TC-%3A-O(N)-SC-(N)
class Solution: def solve(self , root , s): if(not root): return 0; s = s*10 + root.val if(not root.left and not root.right): return s return self.solve(root.left , s) + self.solve(root.right , s) def sumNumbers(self, root: Optional[TreeNode]) -> int: return self.solve(root, 0)
sum-root-to-leaf-numbers
python easy dfs solution TC : O(N) SC (N)
rajitkumarchauhan99
0
20
sum root to leaf numbers
129
0.588
Medium
1,521
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/2421822/Python3-or-collect-num-from-root-2-leaf-join-list-of-'nums'-and-then-return-int
class Solution: def helper(self, node: Optional[TreeNode], nums=[])-> int: if not node: return 0 nums += [node.val] if not node.left and not node.right: num_str = ''.join([str(n) for n in nums]) return int(num_str) return self.helper(node.left, nums.copy()) + self.helper(node.right, nums.copy()) def sumNumbers(self, root: Optional[TreeNode]) -> int: return self.helper(root, [])
sum-root-to-leaf-numbers
Python3 | collect num from root 2 leaf, join list of 'nums' and then return int
Ploypaphat
0
13
sum root to leaf numbers
129
0.588
Medium
1,522
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1984633/Simple-Recursive-Solution-In-Python
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: self.ans = 0 def trav(root,val): if not root: return root val += str(root.val) if not root.left and not root.right: self.ans += int(val) trav(root.left,val) trav(root.right,val) trav(root,'') return self.ans
sum-root-to-leaf-numbers
Simple Recursive Solution In Python
gamitejpratapsingh998
0
62
sum root to leaf numbers
129
0.588
Medium
1,523
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1845919/Python3-Solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: arr=[] def helper(s,root): if not root.left and not root.right: arr.append(int(s+str(root.val))) return if root.left: helper(s+str(root.val),root.left) if root.right: helper(s+str(root.val),root.right) helper("",root) return sum(arr)
sum-root-to-leaf-numbers
Python3 Solution
eaux2002
0
21
sum root to leaf numbers
129
0.588
Medium
1,524
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1835116/Python-Recursion-with-helper
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: if root.val is None: return 0 elif root.right is None and root.left is None: return root.val else: s = str(root.val) lst = self.sum_number_helper(root.left, s) lst += self.sum_number_helper(root.right, s) return sum(lst) def sum_number_helper(self, root, s): if root is None or root.val is None: return [] elif root.right is None and root.left is None: return [int(s + str(root.val))] else: lst = [] s += str(root.val) lst.extend(self.sum_number_helper(root.right, s)) lst.extend(self.sum_number_helper(root.left, s)) return lst```
sum-root-to-leaf-numbers
Python - Recursion with helper
omaralawadhi
0
30
sum root to leaf numbers
129
0.588
Medium
1,525
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1761068/Silly-1-line-solution
class Solution: def sumNumbers(self, n: Optional[TreeNode], path=0) -> int: return (0 if n.left is None else self.sumNumbers(n.left, 10*path + n.val)) + (0 if n.right is None else self.sumNumbers(n.right, 10*path + n.val)) + (10*path + n.val if n.left is None and n.right is None else 0)
sum-root-to-leaf-numbers
Silly 1 line solution
JingXiaoLuo
0
63
sum root to leaf numbers
129
0.588
Medium
1,526
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1724135/Python3-simple-solution-using-queue
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: queue = [(root,str(root.val))] count = 0 while queue: flag = 0 node, s = queue.pop(0) if node.left: queue.append((node.left, s + str(node.left.val))) else: flag += 1 if node.right: queue.append((node.right, s + str(node.right.val))) else: flag += 1 if flag == 2: count += int(s) return count
sum-root-to-leaf-numbers
Python3 simple solution using queue
EklavyaJoshi
0
34
sum root to leaf numbers
129
0.588
Medium
1,527
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1579862/python3-Solution-or-4-line-answer
class Solution: def sumNumbers(self, root ,ans = 0) -> int: if not root: return 0 ans = ans*10 + root.val if (not root.left) and (not root.right): return ans return self.sumNumbers(root.left,ans)+self.sumNumbers(root.right,ans)
sum-root-to-leaf-numbers
python3 Solution | 4 line answer
satyam2001
0
59
sum root to leaf numbers
129
0.588
Medium
1,528
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1558138/Python-Simple-recursive-solution
class Solution: def dfs(self, node, partial): global ans if node == None: return if node.left == None and node.right == None: ans += int(partial+str(node.val)) return self.dfs(node.left, partial+str(node.val)) self.dfs(node.right, partial+str(node.val)) def sumNumbers(self, root: Optional[TreeNode]) -> int: if root == None: return 0 partial = '' global ans ans = 0 self.dfs(root, partial) return ans
sum-root-to-leaf-numbers
[Python] Simple recursive solution
mizan-ali
0
37
sum root to leaf numbers
129
0.588
Medium
1,529
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557846/Python3-with-recursive-depth-first-search
class Solution: path = [] sol = 0 def sumNumbers(self, root: Optional[TreeNode]) -> int: self.path.append(str(root.val)) if root.left == None and root.right == None: self.sol += int("".join(self.path)) if root.left: self.sumNumbers(root.left) if root.right: self.sumNumbers(root.right) self.path.pop() return self.sol
sum-root-to-leaf-numbers
Python3 with recursive depth first search
__Br1__
0
44
sum root to leaf numbers
129
0.588
Medium
1,530
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557569/Python-DFS-solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def dfs(node, num): if not node: return if not node.left and not node.right: #leaf node self.res += int(''.join(num) + str(node.val)) return dfs(node.left, num + [str(node.val)]) dfs(node.right, num + [str(node.val)]) self.res = 0 dfs(root, []) return self.res
sum-root-to-leaf-numbers
Python DFS solution
abkc1221
0
18
sum root to leaf numbers
129
0.588
Medium
1,531
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557311/Python3-Easy-Solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: if not root: return 0 p = {root: root.val} c = dict() res = 0 while p: for node, number in p.items(): if node.left: c[node.left] = number*10 + node.left.val if node.right: c[node.right] = number*10 + node.right.val if not node.left and not node.right: res += number p = c c = dict() return res
sum-root-to-leaf-numbers
Python3 Easy Solution
VicV13
0
17
sum root to leaf numbers
129
0.588
Medium
1,532
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557118/Python-consice-DFS-solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: paths = [] def dfs(node, runningSum): if not node: return if not node.right and not node.left: newSum = runningSum + str(node.val) paths.append(newSum) return newSum = runningSum + str(node.val) dfs(node.left, newSum) dfs(node.right, newSum) dfs(root, '') return sum(map(int, paths))
sum-root-to-leaf-numbers
Python consice DFS solution
vineeth_moturu
0
26
sum root to leaf numbers
129
0.588
Medium
1,533
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1556748/Python3-DFS-Solution-with-Explanation-or-5-Lines-or-96-faster-or-LC-Daily-Challenge-Nov3-2021
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def sumnumbers(root,res): if root is None: return 0 res=int(str(res)+str(root.val)) if root.left == root.right == None: return res return sumnumbers(root.left,res)+sumnumbers(root.right,res) return sumnumbers(root,0)
sum-root-to-leaf-numbers
[Python3] DFS Solution with Explanation | 5 Lines | 96% faster | LC Daily Challenge Nov3 2021
suhana9010
0
31
sum root to leaf numbers
129
0.588
Medium
1,534
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1556597/Python3-or-String-Based-Approach-or-Recursion-or-Simple-Explanation
class Solution: def _create_numbers(self, root): if not root: return [] if not root.left and not root.right: return [f'{root.val}'] _curr = root.val _left_numbers = self._create_numbers(root.left) _right_numbers = self._create_numbers(root.right) _all_numbers = [] for k in (_left_numbers + _right_numbers): _all_numbers.append(f'{_curr}{k}') return _all_numbers def sumNumbers(self, root: Optional[TreeNode]) -> int: _all_numbers = self._create_numbers(root) _sum = 0 for k in _all_numbers: _sum += int(k) return _sum
sum-root-to-leaf-numbers
Python3 | String Based Approach | Recursion | Simple Explanation
tg68
0
15
sum root to leaf numbers
129
0.588
Medium
1,535
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1556273/Python-or-Simple-DFS-or-Preorder-or-90
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: ans = 0 def dfs(root: Optional[TreeNode], s: int) -> int: nonlocal ans if not root: return if not(root.left or root.right): ans += s + root.val return s += root.val dfs(root.left, s * 10) dfs(root.right, s * 10) dfs(root, 0) return ans
sum-root-to-leaf-numbers
Python | Simple DFS | Preorder | 90%
PuneethaPai
0
34
sum root to leaf numbers
129
0.588
Medium
1,536
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1556025/Python-One-liner-Recursion%3A-Easy-to-understand-with-Explanation
class Solution: def sumNumbers(self, root: TreeNode, curr: Optional[int] = 0) -> int: """ Recursively traverse to the leaf nodes of a given binary tree and obtain total sum. :param root: The root node of the binary tree. Note that there is at least 1 node in the tree, so we can guarantee that root is a TreeNode. :param curr: The current obtained number after traversing through the tree to this current node. When the function is just called, curr = 0 since we have not yet traversed. :returns: The sum of the obtained numbers from traversing through the tree. """ # calculate the new current number, by using the formula curr = curr * 10 + root.val # determine type of node: if not (root.left or root.right): # this is a leaf node, traversion stops here, return obtained number return curr else: # this is not a leaf node, we need to obtain the sum of the two subtrees (if it exists) result = 0 if root.left: # root.left contains a leaf node, traverse there result += self.sumNumbers(root.left, curr) if root.right: # root.right contains a leaf node, traverse there result += self.sumNumbers(root.right, curr) return result
sum-root-to-leaf-numbers
Python One-liner Recursion: Easy-to-understand with Explanation
zayne-siew
0
63
sum root to leaf numbers
129
0.588
Medium
1,537
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1556025/Python-One-liner-Recursion%3A-Easy-to-understand-with-Explanation
class Solution: def sumNumbers(self, root: TreeNode, curr: Optional[int] = 0) -> int: return ((self.sumNumbers(root.left, curr*10+root.val) if root.left else 0) + (self.sumNumbers(root.right, curr*10+root.val) if root.right else 0)) if root.left or root.right else (curr*10+root.val)
sum-root-to-leaf-numbers
Python One-liner Recursion: Easy-to-understand with Explanation
zayne-siew
0
63
sum root to leaf numbers
129
0.588
Medium
1,538
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1555861/python-ez-solution
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: output = 0 curr = '' stack = [(root, curr)] while stack: vertex,curr = stack.pop() curr += str(vertex.val) if not vertex.left and not vertex.right: output += int(curr) if vertex.left: stack.append((vertex.left, curr)) if vertex.right: stack.append((vertex.right, curr)) return output
sum-root-to-leaf-numbers
python ez solution
yingziqing123
0
24
sum root to leaf numbers
129
0.588
Medium
1,539
https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1482574/Simple-oror-Easy-Approach-oror-97-Faster
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def path(root,local): nonlocal res if root is None: return if root.left is None and root.right is None: res.append(local*10+root.val) return path(root.left,local*10+root.val) path(root.right,local*10+root.val) res = [] path(root,0) return sum(res)
sum-root-to-leaf-numbers
📌📌 Simple || Easy-Approach || 97% Faster 🐍
abhi9Rai
0
52
sum root to leaf numbers
129
0.588
Medium
1,540
https://leetcode.com/problems/surrounded-regions/discuss/558746/Python-DFS-Easy-solution-with-comments
class Solution: def dfs(self,board,i,j): if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!='O': return board[i][j]='$' # converting to a dollar sign self.dfs(board,i+1,j) self.dfs(board,i-1,j) self.dfs(board,i,j+1) self.dfs(board,i,j-1) def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if len(board)==0: return None m=len(board) n=len(board[0]) for i in range(m): # call dfs on all border 'O's and turn them to '$' for j in range(n): if i==0 or i==m-1: self.dfs(board,i,j) if j==0 or j==n-1: self.dfs(board,i,j) #all border O and others connected them were already converted to $ sign #so left out zeros are surely surrounded by 'X' . Turn all of them to 'X' for i in range(m): for j in range(n): if board[i][j]=='O': board[i][j]='X' # turn the border zeros and their adjacents to their initial form. ie $ -> O for i in range(m): for j in range(n): if board[i][j]=='$': board[i][j]='O'
surrounded-regions
Python DFS Easy solution with comments
JoyRafatAshraf
12
440
surrounded regions
130
0.361
Medium
1,541
https://leetcode.com/problems/surrounded-regions/discuss/1552267/Question-Explanation-is-very-Bad-oror-Well-Explained-Question-and-Solution-oror-Easy
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m,n = len(board),len(board[0]) def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or board[i][j]!="O": return board[i][j] = "*" dfs(i+1,j) dfs(i-1,j) dfs(i,j+1) dfs(i,j-1) return for i in range(m): dfs(i,0) dfs(i,n-1) for j in range(n): dfs(0,j) dfs(m-1,j) for i in range(m): for j in range(n): if board[i][j] == "*": board[i][j] = "O" elif board[i][j] == "O": board[i][j] = "X" return
surrounded-regions
📌📌 Question Explanation is very Bad || Well-Explained Question and Solution || Easy 🐍
abhi9Rai
6
145
surrounded regions
130
0.361
Medium
1,542
https://leetcode.com/problems/surrounded-regions/discuss/1189857/DFS-oror-PYTHON-oror-98-faster-oror-Easy-to-understand
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or board[i][j]!='O': return board[i][j]="*" dfs(i+1,j) dfs(i-1,j) dfs(i,j+1) dfs(i,j-1) m=len(board) n=len(board[0]) if m<3 or n<3: return for i in range(m): dfs(i,0) dfs(i,n-1) for j in range(n): dfs(0,j) dfs(m-1,j) for i in range(m): for j in range(n): if board[i][j]=="*": board[i][j]="O" elif board[i][j]=="O": board[i][j]="X" return
surrounded-regions
DFS || PYTHON || 98% faster || Easy to understand
abhi9Rai
3
199
surrounded regions
130
0.361
Medium
1,543
https://leetcode.com/problems/surrounded-regions/discuss/1156085/Python3-DFS-faster-than-98
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ rows = len(board) if rows <= 2: return board cols = len(board[0]) if cols <= 2: return board def replace(i, j): if i < 0 or i > rows - 1 or j < 0 or j > cols - 1: return if board[i][j] != 'O': return board[i][j] = '#' replace(i, j + 1) replace(i, j - 1) replace(i + 1, j) replace(i - 1, j) for i in range(rows): replace(i, 0) replace(i, cols - 1) for i in range(cols): replace(0, i) replace(rows - 1, i) for i in range(rows): for j in range(cols): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == '#': board[i][j] = 'O'
surrounded-regions
Python3 DFS faster than 98%
faris-shi
3
136
surrounded regions
130
0.361
Medium
1,544
https://leetcode.com/problems/surrounded-regions/discuss/2287456/Python3-oror-98-Faster-and-Efficient-oror-Easy-and-Explained
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def bfs(r, c): q = deque([(r,c)]) while q: r, c = q.popleft() if board[r][c] == 'O': board[r][c] = 'N' for dr, dc in [[r+1,c], [r-1,c], [r,c+1], [r,c-1]]: if (dr in range(len(board)) and dc in range(len(board[0])) and board[dr][dc] == 'O'): q.append((dr, dc)) n, m = len(board), len(board[0]) for i in range(m): if board[0][i] == 'O': bfs(0, i) if board[n-1][i] == 'O': bfs(n-1, i) for i in range(n): if board[i][0] == 'O': bfs(i, 0) if board[i][m-1] == 'O': bfs(i, m-1) for i in range(n): for j in range(m): if board[i][j] == 'X': continue elif board[i][j] == 'N': board[i][j] = 'O' else: board[i][j] = 'X'
surrounded-regions
Python3 || 98% Faster and Efficient || Easy & Explained
Dewang_Patil
2
95
surrounded regions
130
0.361
Medium
1,545
https://leetcode.com/problems/surrounded-regions/discuss/2186815/Python-DFS-with-full-working-explanation
class Solution: def solve(self, board: List[List[str]]) -> None: rows, cols = len(board), len(board[0]) def capture(r, c): if r < 0 or c < 0 or r == rows or c == cols or board[r][c] != 'O': # index bounds conditions return board[r][c] = 'T' capture(r + 1, c) # down capture(r - 1, c) # up capture(r, c + 1) # right capture(r, c - 1) # left # DFS: Capture un-surrounded regions (O -> T) for r in range(rows): for c in range(cols): if board[r][c] == 'O' and (r in [0, rows - 1] or c in [0, cols - 1]): # Only the O's who is in the wall region will be chosen capture(r, c) # Capture surrounded regions (O -> X) for r in range(rows): for c in range(cols): if board[r][c] == 'O': board[r][c] = 'X' # Un-capture un-surrounded regions(T -> O) for r in range(rows): for c in range(cols): if board[r][c] == 'T': board[r][c] = 'O'
surrounded-regions
Python DFS with full working explanation
DanishKhanbx
2
62
surrounded regions
130
0.361
Medium
1,546
https://leetcode.com/problems/surrounded-regions/discuss/1552007/Different-Approach-or-Union-Find-or-Python-or-Explanation
class DisjointSet: def __init__(self, n): self.n = n self.id = [0]*n for i in range(n): self.id[i] = i def find(self, i:int) -> int: while(i!=self.id[i]): self.id[i] = self.id[self.id[i]] i = self.id[i] return i def union(self, p, q) -> bool: idp = self.find(p) idq = self.find(q) if idp == idq: return False self.id[idp] = idq return True def isConnected(self, p:int, q:int) -> bool: idp = self.find(p) idq = self.find(q) if idp == idq: return True return False class Solution: def getId(self, i:int, j:int, m:int, n:int) -> int: return i*n+j def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) total = m*n TOP = total RIGHT = total+1 BOTTOM = total+2 LEFT = total+3 ds = DisjointSet(total+4) for j in range(n): if board[0][j] == "O": ds.union(self.getId(0,j,m,n), TOP) if board[m-1][j] == "O": ds.union(self.getId(m-1,j,m,n), BOTTOM) for i in range(m): if board[i][0] == "O": ds.union(self.getId(i,0,m,n), LEFT) if board[i][n-1] == "O": ds.union(self.getId(i,n-1,m,n), RIGHT) for i in range(m): for j in range(n): for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]: newI = i+x newJ = j+y if 0<=newI<=m-1 and 0<=newJ<=n-1: if board[i][j] == board[newI][newJ] and board[i][j] == "O": ds.union(self.getId(i,j,m,n), self.getId(newI,newJ,m,n)) for i in range(m): for j in range(n): identifier = self.getId(i,j,m,n) if not any(ds.isConnected(identifier, side) for side in [LEFT, RIGHT, TOP, BOTTOM]): board[i][j] = 'X'
surrounded-regions
Different Approach | Union Find | Python | Explanation
CaptainX
2
310
surrounded regions
130
0.361
Medium
1,547
https://leetcode.com/problems/surrounded-regions/discuss/452471/Python-with-clear-BFS-solution-144ms.
class Solution: def solve(self, board: List[List[str]]) -> None: if not board or board is None: return row, col = len(board), len(board[0]) queueBorder = collections.deque([]) for i in range(row): for j in range(col): if (i == 0 or i == row - 1 or j == 0 or j == col - 1) and board[i][j] == 'O': board[i][j] = 'P' queueBorder.append((i,j)) while queueBorder: x, y = queueBorder.popleft() for dx, dy in [(1,0), (0,1), (-1,0), (0,-1)]: newX, newY = x + dx, y + dy if 0 <= newX < row and 0 <= newY < col and board[newX][newY] == 'O': board[newX][newY] = 'P' queueBorder.append((newX, newY)) for i in range(row): for j in range(col): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == 'P': board[i][j] = 'O'
surrounded-regions
Python with clear BFS solution, 144ms.
yzfeng89
2
118
surrounded regions
130
0.361
Medium
1,548
https://leetcode.com/problems/surrounded-regions/discuss/2652417/Python-way-Simple-DFS
class Solution: def solve(self, mat: List[List[str]]) -> None: n=len(mat) m=len(mat[0]) def dfs(i,j): visited[i][j]=1 dir = [[-1,0],[0,1],[1,0],[0,-1]] for a,b in dir: row = a+i col = b+j if row>=0 and row<n and col>=0 and col<m and mat[row][col]=='O' and not visited[row][col]: dfs(row,col) visited = [[0 for _ in range(m)] for i in range(n)] for j in range(m): if not visited[0][j] and mat[0][j]=='O': dfs(0,j) if not visited[n-1][j] and mat[n-1][j]=='O': dfs(n-1,j) for i in range(n): if not visited[i][0] and mat[i][0]=='O': dfs(i,0) if not visited[i][m-1] and mat[i][m-1]=='O': dfs(i,m-1) for i in range(n): for j in range(m): if not visited[i][j] and mat[i][j]=='O': mat[i][j]='X' return mat
surrounded-regions
Python way - Simple DFS
prateekgoel7248
1
75
surrounded regions
130
0.361
Medium
1,549
https://leetcode.com/problems/surrounded-regions/discuss/2445767/Python-2-color-technique
class Solution: def solve(self, board: List[List[str]]) -> None: ## dfs solution row = len(board) col = len(board[0]) visited = set() def dfs(board, x, y, visited): if x<0 or y< 0 or x>= row or y >= col or (x,y) in visited or board[x][y] != 'O': return visited.add((x,y)) board[x][y] = '1' for i,j in [[1,0],[-1,0],[0,1],[0,-1]]: dfs(board, x+i, y+j, visited) # calling for 4 boundary for j in range(col): dfs(board, row-1, j, visited) for j in range(col): dfs(board, 0, j, visited) for j in range(row): dfs(board, j, 0, visited) for j in range(row): dfs(board, j, col-1, visited) for i in range(row): for j in range(col): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == '1': board[i][j] = 'O'
surrounded-regions
Python 2 color technique
Abhi_009
1
52
surrounded regions
130
0.361
Medium
1,550
https://leetcode.com/problems/surrounded-regions/discuss/2034976/python-3-step-easy-and-efficient-DFS-solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ #step 2 def dfs(r, c) : if board[r][c] == "O" and (r,c) not in s : s.add((r,c)) if r-1 >= 0 : dfs(r-1, c) if r+1 < len(board) : dfs(r+1, c) if c-1 >= 0 : dfs(r, c-1) if c+1 < len(board[0]) : dfs(r, c+1) #step 1 s = set() for i in range(len(board)) : for j in range(len(board[0])) : if i == 0 or j == 0 or i == len(board)-1 or j == len(board[0])-1 : if board[i][j] == "O" and (i, j) not in s : dfs(i, j) #step 3 for i in range(1, len(board)-1) : for j in range(1, len(board[0])-1) : if board[i][j] == "O" and (i, j) not in s : board[i][j] = "X" return board
surrounded-regions
python 3 step easy and efficient DFS solution
runtime-terror
1
64
surrounded regions
130
0.361
Medium
1,551
https://leetcode.com/problems/surrounded-regions/discuss/2028067/Python-dfs-solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ visited = set() def dfs(i, j, visited): if (i, j) in visited: return if board[i][j] == 'X': return visited.add((i, j)) for child in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)): if 0 <= child[0] < len(board) and 0 <= child[1] < len(board[0]): dfs(child[0], child[1], visited) for i in range(len(board)): for j in range(len(board[0])): if i == 0 or i == len(board) - 1 or j == 0 or j == len(board[0]) - 1: if (i, j) not in visited: dfs(i, j, visited) for i in range(len(board)): for j in range(len(board[0])): if (i, j) not in visited: board[i][j] = "X" return board
surrounded-regions
Python dfs solution
user6397p
1
44
surrounded regions
130
0.361
Medium
1,552
https://leetcode.com/problems/surrounded-regions/discuss/1983363/Python3-Runtime%3A-156ms-73.98-Memory%3A-16mb-50.42
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ rows, cols = len(board), len(board[0]) self.getBoardRegions(board, rows, cols) self.changeUnVisitedRegions(board, rows, cols) self.changeBoarderSymbol(board, rows, cols) return board # get the regions of the board def getBoardRegions(self, board, rows, cols): for r in range(rows): for c in range(cols): if board[r][c] == 'O' and (r in [0, rows - 1]) or (c in [0, cols - 1]): self.captureBoarders(board, r, c) # capture means this function will # change the board's connect regions to 'T' def captureBoarders(self, board, r, c): if r < 0 or r >= len(board) or c < 0 or c >= len(board[0]) or board[r][c] != 'O': return if board[r][c] == 'O': board[r][c] = 'T' self.captureBoarders(board, r - 1, c) # UP self.captureBoarders(board, r + 1, c) # DOWN self.captureBoarders(board, r, c + 1) # LEFT self.captureBoarders(board, r, c - 1) # RIGHT # if a regions is still 'O' and haven't been 'T' yet it # means its not connected with any board regions # so simply change them to 'X' def changeUnVisitedRegions(self, board, rows, cols): for r in range(rows): for c in range(cols): if board[r][c] == 'O': board[r][c] = 'X' # remember we have change our connect 'O' to 'T' # now its time to make it back to 'O' def changeBoarderSymbol(self, board, rows, cols): for r in range(rows): for c in range(cols): if board[r][c] == 'T': board[r][c] = 'O'
surrounded-regions
Python3 Runtime: 156ms 73.98% Memory: 16mb 50.42%
arshergon
1
51
surrounded regions
130
0.361
Medium
1,553
https://leetcode.com/problems/surrounded-regions/discuss/1812247/Solution-that-you-want-%3A
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def bfs(board,i,j): if i>=0 and j>=0 and i<len(board) and j<len(board[0]) and board[i][j]=='O': board[i][j]='A' bfs(board,i+1,j) bfs(board,i-1,j) bfs(board,i,j+1) bfs(board,i,j-1) m,n=len(board),len(board[0]) for p in range(n): # this loop will take care of boundary elements top and bottom row bfs(board,0,p) bfs(board,m-1,p) for q in range(m): # this loop will take care of left and right column boundary. bfs(board,q,0) bfs(board,q,n-1) for p in range(m): for q in range(n): if board[p][q]=='O': board[p][q]='X' elif board[p][q]=='A': board[p][q]='O'
surrounded-regions
Solution that you want :
goxy_coder
1
77
surrounded regions
130
0.361
Medium
1,554
https://leetcode.com/problems/surrounded-regions/discuss/1462844/WEEB-DOES-PYTHON-BFS
class Solution: def solve(self, board: List[List[str]]) -> None: row, col = len(board), len(board[0]) queue = deque([(0,i) for i in range(col) if board[0][i] == "O"]+ [(row-1,i) for i in range(col) if board[row-1][i] == "O"] + [(i,0) for i in range(1,row-1) if board[i][0] == "O"] + [(i,col-1) for i in range(1,row-1) if board[i][col-1] == "O"]) # get all borders on the board self.bfs(queue, row, col, board) for x in range(row): for y in range(col): if board[x][y] == "O": board[x][y] = "X" if board[x][y] == "V": board[x][y] = "O" return board def bfs(self, queue, row, col, board): while queue: x, y = queue.popleft() if board[x][y] == "V": continue board[x][y] = "V" for nx, ny in [[x+1,y], [x-1,y], [x,y+1], [x,y-1]]: if 0<=nx<row and 0<=ny<col and board[nx][ny] == "O": queue.append((nx,ny))
surrounded-regions
WEEB DOES PYTHON BFS
Skywalker5423
1
111
surrounded regions
130
0.361
Medium
1,555
https://leetcode.com/problems/surrounded-regions/discuss/1247595/Easy-and-simple-Python-DFS-approach
class Solution: def dfs(self, board, i, j): if 0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == 'O': board[i][j] = 'E' self.dfs(board, i+1, j) self.dfs(board, i-1, j) self.dfs(board, i, j+1) self.dfs(board, i, j-1) def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ row=len(board) col=len(board[0]) if row==0: return #first and last row for i in range(col): if board[0][i]=="O": self.dfs(board, 0, i) if board[row-1][i]=="O": self.dfs(board, row-1, i) #first and last col for i in range(row): if board[i][0]=="O": self.dfs(board,i,0) if board[i][col-1]=="O": self.dfs(board, i,col-1) for i in range(row): for j in range(col): if board[i][j]=='O': board[i][j]='X' elif board[i][j]=='E': board[i][j]='O'
surrounded-regions
Easy and simple Python DFS approach
jaipoo
1
279
surrounded regions
130
0.361
Medium
1,556
https://leetcode.com/problems/surrounded-regions/discuss/692254/Python3-12-line-flood-fill-(98.83)
class Solution: def solve(self, board: List[List[str]]) -> None: m, n = len(board), len(board[0]) def fn(i, j): """Flood fill "O" with sentinel""" if 0 <= i < m and 0 <= j < n and board[i][j] == "O": board[i][j] = "#" #sentinel for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): fn(ii, jj) for i in range(m): fn(i, 0) or fn(i, n-1) for j in range(n): fn(0, j) or fn(m-1, j) for i in range(m): for j in range(n): if board[i][j] == "O": board[i][j] = "X" if board[i][j] == "#": board[i][j] = "O"
surrounded-regions
[Python3] 12-line flood fill (98.83%)
ye15
1
43
surrounded regions
130
0.361
Medium
1,557
https://leetcode.com/problems/surrounded-regions/discuss/692254/Python3-12-line-flood-fill-(98.83)
class Solution: def solve(self, board: List[List[str]]) -> None: m, n = len(board), len(board[0]) stack = [] for i in range(m): for j in range(n): if (i in (0, m-1) or j in (0, n-1)) and board[i][j] == 'O': board[i][j] = '#' stack.append((i, j)) while stack: i, j = stack.pop() for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and board[ii][jj] == 'O': board[ii][jj] = '#' stack.append((ii, jj)) for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == '#': board[i][j] = 'O'
surrounded-regions
[Python3] 12-line flood fill (98.83%)
ye15
1
43
surrounded regions
130
0.361
Medium
1,558
https://leetcode.com/problems/surrounded-regions/discuss/2830534/BFS-(Personal-Notes)
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ if not board or not board[0]: return self.ROWS = len(board) self.COLS = len(board[0]) # Step 1). retrieve all border cells from itertools import product borders = list(product(range(self.ROWS), [0, self.COLS-1])) \ + list(product([0, self.ROWS-1], range(self.COLS))) # Step 2). mark the "escaped" cells, with any placeholder, e.g. 'E' for row, col in borders: #self.DFS(board, row, col) self.BFS(board, row, col) # Step 3). flip the captured cells ('O'->'X') and the escaped one ('E'->'O') for r in range(self.ROWS): for c in range(self.COLS): if board[r][c] == 'O': board[r][c] = 'X' # captured elif board[r][c] == 'E': board[r][c] = 'O' # escaped def BFS(self, board, row, col): from collections import deque queue = deque([(row, col)]) while queue: (row, col) = queue.popleft() if board[row][col] != 'O': continue # mark this cell as escaped board[row][col] = 'E' # check its neighbor cells if col < self.COLS-1: queue.append((row, col+1)) if row < self.ROWS-1: queue.append((row+1, col)) if col > 0: queue.append((row, col-1)) if row > 0: queue.append((row-1, col))
surrounded-regions
BFS (Personal Notes)
Farawayy
0
1
surrounded regions
130
0.361
Medium
1,559
https://leetcode.com/problems/surrounded-regions/discuss/2827472/Easy-to-understand-python-solution-using-DFS.
class Solution: def solve(self, board: List[List[str]]) -> None: m, n = len(board), len(board[0]) vis = [] for i in range(m): temp = [] for j in range(n): temp.append(0) vis.append(temp) // marking all the "O" accessible from the boundary for i in range(m): for j in range(n): if (board[i][j] == 'O') and (i == 0 or i == m-1 or j == 0 or j == n-1): self.dfs(board, i, j, m, n, vis) // changing all the unaccessible "O" to "X" for i in range(1, m-1): for j in range(1, n-1): if board[i][j] == 'O' and vis[i][j] == 0: board[i][j] = 'X' def dfs(self, board, i, j, m, n, vis): if i < 0 or i >= m or j < 0 or j >= n: return if vis[i][j] == 1: return if board[i][j] == 'X': return vis[i][j] = 1 self.dfs(board, i-1, j, m, n, vis) self.dfs(board, i+1, j, m, n, vis) self.dfs(board, i, j-1, m, n, vis) self.dfs(board, i, j+1, m, n, vis)
surrounded-regions
Easy to understand python solution using DFS.
i-haque
0
3
surrounded regions
130
0.361
Medium
1,560
https://leetcode.com/problems/surrounded-regions/discuss/2825948/Python3-DFS-and-Union-Find-methods
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ # Method1: DFS. def dfs(x, y): if x < 0 or x > len(board)-1 or y < 0 or y > len(board[0])-1 or board[x][y] != 'O': return board[x][y] = 'A' dfs(x+1, y) # Down dfs(x-1, y) # Up dfs(x, y-1) # Left dfs(x, y+1) # Right return m, n = len(board), len(board[0]) # m = row, n = col for i in range(m): dfs(i, 0) # First col dfs(i, n-1) # Last col for j in range(n): dfs(0, j) # First row dfs(m-1, j) # Last row for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == 'A': board[i][j] = 'O' return
surrounded-regions
[Python3] DFS and Union Find methods
Cceline00
0
3
surrounded regions
130
0.361
Medium
1,561
https://leetcode.com/problems/surrounded-regions/discuss/2825948/Python3-DFS-and-Union-Find-methods
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ # Method2: UnionFind. def find(x): # Find parent if parents[x] != x: parents[x] = find(parents[x]) return parents[x] # return parents[x] not x def union(x, y): px, py = find(x), find(y) if px != py: parents[px] = py # Left tree merges into the right tree return def isConnected(x, y): return find(x) == find(y) m, n = len(board), len(board[0]) if m <= 1: return parents = {i:i for i in range(m*n+1)} # m*n for dummy head. for i in range(m): for j in range(n): if board[i][j] == 'O': if i == 0 or i == m-1 or j == 0 or j == n-1: # On the border union(i*n+j, m*n) else: if board[i-1][j] == 'O': # Up union((i-1)*n+j, i*n+j) if board[i+1][j] == 'O': # Down union((i+1)*n+j, i*n+j) if board[i][j-1] == 'O': # Left union(i*n+(j-1), i*n+j) if board[i][j+1] == 'O': # Right union(i*n+(j+1), i*n+j) for i in range(m): for j in range(n): if not isConnected(i*n+j, m*n): board[i][j] = 'X' return
surrounded-regions
[Python3] DFS and Union Find methods
Cceline00
0
3
surrounded regions
130
0.361
Medium
1,562
https://leetcode.com/problems/surrounded-regions/discuss/2803618/Python-Easy-linear-solution-with-explanations-no-additional-memory
class Solution: def solve(self, board: List[List[str]]) -> None: m = len(board) n = len(board[0]) # Recursive filling of the region def fill_area(y,x: int): if y < 0 or x < 0 or y >= m or x >= n: return if board[y][x] == 'Y': board[y][x] = 'O' fill_area(y-1,x) fill_area(y+1,x) fill_area(y,x-1) fill_area(y,x+1) # 1. Replace all 'O' with 'Y' for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'Y' # 2. Fill all edge 'Y'-regions with 'O' for i in range(m): fill_area(i,0) fill_area(i,n-1) for j in range(n): fill_area(0, j) fill_area(m-1, j) # 3. Fill all 'Y' that is left with 'X' for i in range(m): for j in range(n): if board[i][j] == 'Y': board[i][j] = 'X'
surrounded-regions
[Python] Easy linear solution with explanations, no additional memory
dlesha
0
7
surrounded regions
130
0.361
Medium
1,563
https://leetcode.com/problems/surrounded-regions/discuss/2789805/Python-or-Easy-intuitive-DFS-solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ rows, cols = len(board), len(board[0]) visited = set() def dfs(r, c): if r not in range(rows) or c not in range(cols) or (r, c) in visited or board[r][c] == 'X': return visited.add((r, c)) dfs(r, c + 1) dfs(r, c - 1) dfs(r + 1, c) dfs(r - 1, c) for r in range(rows): for c in range(cols): if ((r, c) not in visited and board[r][c] == 'O' and (r == 0 or r == rows - 1 or c == 0 or c == cols - 1)): dfs(r, c) for r in range(rows): for c in range(cols): if (r, c) not in visited and board[r][c] == 'O': board[r][c] = 'X'
surrounded-regions
Python | Easy intuitive DFS solution
KevinJM17
0
9
surrounded regions
130
0.361
Medium
1,564
https://leetcode.com/problems/surrounded-regions/discuss/2781649/Python-oror-Iterative-DFS
class Solution: def solve(self, board: List[List[str]]) -> None: n, m = len(board), len(board[0]) adj = [(-1,0), (0,1), (1,0), (0,-1)] graph = defaultdict(list) for i in range(n): for j in range(m): for r,c in adj: if not (0 <= i + r < n and 0 <= j + c < m): continue graph[(i,j)].append((i+r,j+c)) coast = set() def dfs(i,j): nonlocal coast stack = [(i,j)] coast.add((i,j)) visited = set() while stack: node = stack.pop() if node in visited: continue visited.add(node) for r,c in graph[node]: if board[r][c] == 'O': coast.add((r,c)) stack.append((r,c)) return None for j in range(m): if board[0][j] == 'O': dfs(0,j) if board[-1][j] == 'O': dfs(n-1,j) for i in range(n): if board[i][0] == 'O': dfs(i,0) if board[i][-1] == 'O': dfs(i, m-1) for i in range(1,n-1): for j in range(1,m-1): if (i,j) in coast: continue board[i][j] = 'X'
surrounded-regions
Python || Iterative DFS
morpheusdurden
0
7
surrounded regions
130
0.361
Medium
1,565
https://leetcode.com/problems/surrounded-regions/discuss/2744682/Easy-understanding-python-solution
class Solution: def solve(self, b: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m, n = len(b), len(b[0]) def flood(i, j, b): if i < 0 or i >= m or j < 0 or j >= n or b[i][j] != "O": return if b[i][j] == "O": b[i][j] = "A" flood(i + 1, j, b) flood(i - 1, j, b) flood(i, j - 1, b) flood(i, j + 1, b) # flood the "O" in border, for other "O", just change them to "X" for i in range(0, m): flood(i, 0, b) flood(i, n-1, b) for i in range(0, n): flood(0, i, b) flood(m-1, i, b) for i in range(0, m): for j in range(0, n): if b[i][j] == "O": b[i][j] = "X" elif b[i][j] == "A": b[i][j] = "O" else: continue
surrounded-regions
Easy understanding python solution
jackson-cmd
0
4
surrounded regions
130
0.361
Medium
1,566
https://leetcode.com/problems/surrounded-regions/discuss/2742999/Python-DFS-solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ row = len(board) col = len(board[0]) def capture(r, c): if (r<0 or c<0 or r==row or c==col or board[r][c]!="O"): return board[r][c] = "T" capture(r-1, c) capture(r+1, c) capture(r, c-1) capture(r, c+1) for i in range(row): for j in range(col): if board[i][j] == "O" and (i in [0, row-1] or j in [0, col-1]): capture(i, j) for i in range(row): for j in range(col): if board[i][j]=="O": board[i][j]= "X" elif board[i][j]=="T": board[i][j]= "O"
surrounded-regions
Python DFS solution
gcheng81
0
5
surrounded regions
130
0.361
Medium
1,567
https://leetcode.com/problems/surrounded-regions/discuss/2739876/Python-Union-Find-Solution
class UF: def __init__(self, n): self.parent = [i for i in range(n)] self.count = n def _find(self, p): while p != self.parent[p]: self.parent[p] = self.parent[self.parent[p]] p = self.parent[p] return p def _union(self, p, q): rootP = self._find(p) rootQ = self._find(q) if rootP == rootQ: return else: self.parent[rootP] = rootQ self.count -= 1 def _connected(self, p, q): rootP = self._find(p) rootQ = self._find(q) if rootP == rootQ: return True else: return False def _count(self): return self.count class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) dummy = m*n uf = UF(m*n+1) steps = [[0,1],[0,-1],[1,0],[-1,0]] for i in range(m): # union dummy, (i, 0) if board[i][0] == 'O': uf._union(dummy, i*n + 0) # union dummy, (i, n-1) if board[i][n-1] == 'O': uf._union(dummy, i*n + n -1) for j in range(n): # union dummy, (0, j) if board[0][j] == 'O': uf._union(dummy, 0*n + j) # union dummy, (m-1, j) if board[m-1][j] == 'O': uf._union(dummy, (m-1)*n + j) for i in range(1, m-1): for j in range(1, n-1): if board[i][j] == 'O': for step in steps: x = i + step[0] y = j + step[1] if board[x][y] == 'O': uf._union(i*n+j, x*n+y) # flip the not unioned item for i in range(1, m-1): for j in range(1, n-1): if not uf._connected(dummy, i*n+j): board[i][j] = 'X'
surrounded-regions
Python Union Find Solution
Rui_Liu_Rachel
0
3
surrounded regions
130
0.361
Medium
1,568
https://leetcode.com/problems/surrounded-regions/discuss/2739790/Python-Floodfill-Simple-Solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) visited = [[False for _ in range(n)] for _ in range(m)] steps = [[1, 0], [-1, 0], [0, 1], [0, -1]] def traverse(i, j, char): if not 0<=i<m or not 0<=j<n: return if visited[i][j]: return if board[i][j] == 'O': board[i][j] = char for step in steps: x = i + step[0] y = j + step[1] traverse(x, y, char) # flood the edge with 'E' for i in range(m): traverse(i, 0, 'E') traverse(i, n-1, 'E') for j in range(n): traverse(0, j, 'E') traverse(m-1, j, 'E') # flip all 'O' for i in range(m): for j in range(n): if board[i][j] == 'O': traverse(i, j, 'X') # flip back the 'E' for i in range(m): for j in range(n): if board[i][j] == 'E': board[i][j] = 'O' return board
surrounded-regions
Python Floodfill Simple Solution
Rui_Liu_Rachel
0
2
surrounded regions
130
0.361
Medium
1,569
https://leetcode.com/problems/surrounded-regions/discuss/2723871/BFS-Two-Easy-Approaches-in-O(N2)
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def BFS(x, y, rows, columns): q = deque([(x, y)]) while q: x, y = q.popleft() visited.add((x, y)) for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]: nx, ny = dx + x, dy + y if 0 <= nx < rows and 0 <= ny < columns and board[nx][ny] == 'O' and (nx, ny) not in visited: visited.add((nx, ny)) q.append((nx, ny)) rows = len(board) columns = len(board[0]) visited = set() for i in range(rows): if i == 0 or i == rows - 1: for j in range(columns): if board[i][j] == 'O' and (i, j) not in visited: BFS(i, j, rows, columns) else: if board[i][0] == 'O' and (i, 0) not in visited: BFS(i, 0, rows, columns) if board[i][columns - 1] == 'O' and (i, columns - 1) not in visited: BFS(i, columns - 1, rows, columns) for i in range(rows): for j in range(columns): if (i, j) not in visited: board[i][j] = 'X'
surrounded-regions
BFS - Two Easy Approaches in O(N^2)
user6770yv
0
7
surrounded regions
130
0.361
Medium
1,570
https://leetcode.com/problems/surrounded-regions/discuss/2723871/BFS-Two-Easy-Approaches-in-O(N2)
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def capture_if_valid(x, y, rows, columns): q = deque([(x, y)]) visited = set() while q: x, y = q.popleft() visited.add((x, y)) if x == 0 or x == rows - 1 or y == 0 or y == columns - 1: return for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: nx, ny = x + dx, y + dy if 0 <= nx <= rows - 1 and 0 <= ny <= columns - 1: if board[nx][ny] == 'O' and (nx, ny) not in visited: q.append((nx, ny)) visited.add((nx, ny)) for (x, y) in visited: board[x][y] = 'X' rows = len(board) columns = len(board[0]) if rows > 2 and columns > 2: for i in range(1, rows): for j in range(1, columns): if board[i][j] == 'O': capture_if_valid(i, j, rows, columns)
surrounded-regions
BFS - Two Easy Approaches in O(N^2)
user6770yv
0
7
surrounded regions
130
0.361
Medium
1,571
https://leetcode.com/problems/surrounded-regions/discuss/2711298/Python-%2B-Chinese-Comment
class UF: def __init__(self,n): # 存储若干棵树 self.parent = [i for i in range(n)] # 记录树的“重量” self.size = [1 for i in range(n)] # 记录连通分量个数 self.count = n def find(self,x): # 返回节点 x 的根节点 while self.parent[x] != x: # 进行路径压缩 self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x # 将 p 和 q 连通 def union(self,p,q): p_root = self.find(p) q_root = self.find(q) if q_root==p_root: return # 小树接到大树下面,较平衡 if self.size[p_root] > self.size[q_root]: self.parent[q_root] = p_root self.size[p_root] += self.size[q_root] else: self.parent[p_root] = q_root self.size[q_root] += p_root self.count -= 1 # 判断 p 和 q 是否互相连通 def connected(self,p,q): # 处于同一棵树上的节点,相互连通 return self.find(p) == self.find(q) def count(): return self.count class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if len(board)==0:return m = len(board) n = len(board[0]) uf = UF(m*n+1) dummy = m*n # 将首列和末列的 O 与 dummy 连通 for i in range(0,m): if board[i][0]=='O': uf.union(i*n,dummy) print(uf.connected(i*n,dummy)) if board[i][n-1]=='O': uf.union(i*n+n-1,dummy) print(uf.connected(i*n+n-1,dummy)) # 将首行和末行的 O 与 dummy 连通 for j in range(0,n): if board[0][j]=='O': uf.union(j,dummy) print(uf.connected(j,dummy)) if board[m-1][j]=='O': uf.union(n*(m-1)+j,dummy) print(uf.connected(n*(m-1)+j,dummy)) # 方向数组 d 是上下左右搜索的常用手法 d = [[1,0],[-1,0],[0,1],[0,-1]] for i in range(1,m-1): for j in range(1,n-1): if board[i][j]=='O': # 将此 O 与上下左右的 O 连通 for k in range(4): x = i+d[k][0] y = j+d[k][1] if board[x][y] == 'O': uf.union(i*n+j,x*n+y) # 所有不和 dummy 连通的 O,都要被替换 for i in range(1,m-1): for j in range(1,n-1): if not uf.connected(dummy,i*n+j): board[i][j]='X'
surrounded-regions
Python + Chinese Comment
Michael_Songru
0
3
surrounded regions
130
0.361
Medium
1,572
https://leetcode.com/problems/surrounded-regions/discuss/2697826/Dfs
class Solution: def solve(self, matrix: List[List[str]]) -> None: visited = set() #false = set() r, c = len(matrix), len(matrix[0]) def dfs(i, j): if i < 0 or j < 0 or i >= r or j >= c or (i,j) in visited or matrix[i][j] == 'X': return visited.add((i,j)) dfs(i+1, j) dfs(i-1, j) dfs(i, j+1) dfs(i, j-1) for i in range(r): if matrix[i][0] == 'O': dfs(i, 0) if matrix[i][c-1] == 'O': dfs(i, c-1) for j in range(1, c-1): if matrix[0][j] == 'O': dfs(0, j) if matrix[r-1][j] == 'O': dfs(r-1, j) for i in range(1, r): for j in range(1, c): if matrix[i][j] == 'O' and (i, j) not in visited: matrix[i][j] = 'X' """ Do not return anything, modify board in-place instead. """
surrounded-regions
Dfs
mukundjha
0
2
surrounded regions
130
0.361
Medium
1,573
https://leetcode.com/problems/surrounded-regions/discuss/2683173/Python-BFS-oror-Easy-to-understand
class Solution: def solve(self, board: List[List[str]]) -> None: ROWS = len(board) COLS = len(board[0]) def bfs(i, j): seen = set() q = collections.deque() q.append((i, j)) surrounded = True while q: for _ in range(len(q)): i, j = q.popleft() if (i < 0 or j < 0 or i >= ROWS or j >= COLS or board[i][j] != "O" or (i, j) in seen): continue seen.add((i, j)) surrounded &amp;= 0 < i < ROWS - 1 and 0 < j < COLS - 1 q.append((i + 1, j)) q.append((i - 1, j)) q.append((i, j + 1)) q.append((i, j - 1)) if surrounded: for i, j in seen: board[i][j] = "X" for i in range(ROWS): for j in range(COLS): if i != 0 and i != ROWS - 1 and j != 0 and j != COLS - 1 and board[i][j] == "O": bfs(i, j)
surrounded-regions
Python BFS || Easy to understand
yllera
0
6
surrounded regions
130
0.361
Medium
1,574
https://leetcode.com/problems/surrounded-regions/discuss/2681316/DFS-SOLUTION-IN-PYTHON
class Solution: def solve(self, board: List[List[str]]) -> None: def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or board[i][j]!='O': return board[i][j]='#' #CONVERTING TO A DOLLAR SIGN dfs(i+1,j) dfs(i-1,j) dfs(i,j-1) dfs(i,j+1) m,n=len(board),len(board[0]) if m==0: return None for i in range(m): for j in range(n): if i==0 or i==m-1: dfs(i,j)#CALLING DFS ON ALL BORDER 0'S if j==0 or j==n-1: dfs(i,j) for i in range(m): for j in range(n): if board[i][j]=='O': board[i][j]='X'#LEFT OUT ZEROES ARE TURNED TO X for i in range(m): for j in range(n): if board[i][j]=='#': board[i][j]='O'#CONVERTING BORDER ZEROES INTO ORIGINAL FORMS FROM # TO 'o' return board
surrounded-regions
DFS SOLUTION IN PYTHON
shashank_2000
0
28
surrounded regions
130
0.361
Medium
1,575
https://leetcode.com/problems/surrounded-regions/discuss/2666192/Python%3A-BFS-Solution
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ n = len(board) m = len(board[0]) q = deque([]) visited = set() for i in range(n): for j in range(m): if board[i][j] == 'O' and (j == 0 or i == 0 or i == n-1 or j == m - 1): q.append((i,j)) while q: row,col = q.popleft() if (row,col) in visited: continue if row < 0 or row >= n or col <0 or col >= m : continue if board[row][col] == "-1": continue if board[row][col] == "X": continue if board[row][col] == "O": board[row][col] = "-1" visited.add((row, col)) q.append((row+1,col)) q.append((row - 1, col)) q.append((row, col +1 )) q.append((row, col -1)) for i in range(n): for j in range(m): if board[i][j] == "O": board[i][j] = "X" elif board[i][j] == "-1": board[i][j] = "O" return board
surrounded-regions
Python: BFS Solution
vijay_2022
0
4
surrounded regions
130
0.361
Medium
1,576
https://leetcode.com/problems/surrounded-regions/discuss/2640557/Clean-Python3-or-BFS-or-In-Place
class Solution: def solve(self, board: List[List[str]]) -> None: neighbors = [(0, -1), (-1, 0), (0, 1), (1, 0)] def can_reach_edge(st_row, st_col): q, seen = deque([(st_row, st_col)]), {(st_row, st_col)} while q: row, col = q.pop() for r, c in neighbors: if not (0 <= row+r < rows and 0 <= col + c < cols): return True if board[row+r][col+c] == 'O' and (row+r, col+c) not in seen: seen.add((row+r, col+c)) q.appendleft((row+r, col+c)) return False def mark_xs(st_row, st_col): q, seen = deque([(st_row, st_col)]), {(st_row, st_col)} while q: row, col = q.pop() board[row][col] = 'X' for r, c in neighbors: if 0 <= row+r < rows and 0 <= col + c < cols and board[row+r][col+c] == 'O' and (row+r, col+c) not in seen: seen.add((row+r, col+c)) q.appendleft((row+r, col+c)) rows, cols = len(board), len(board[0]) for row in range(rows): for col in range(cols): if board[row][col] == 'O' and not can_reach_edge(row, col): mark_xs(row, col)
surrounded-regions
Clean Python3 | BFS | In Place
ryangrayson
0
58
surrounded regions
130
0.361
Medium
1,577
https://leetcode.com/problems/surrounded-regions/discuss/2627777/python3-oror-easy-oror-dfs-solution
class Solution: def solve(self, board: List[List[str]]) -> None: if not board: return rowSize=len(board) colSize=len(board[0]) visited=[[0]*colSize for i in range(rowSize)] directions=[[-1,0],[1,0],[0,1],[0,-1]] def dfs(row,col): visited[row][col]=1 for r,c in directions: newRow=row+r newCol=col+c if newRow>=0 and newRow<rowSize and newCol>=0 and newCol<colSize and visited[newRow][newCol]==0 and board[newRow][newCol]=="O": dfs(newRow,newCol) #above row for i in range(colSize): if board[0][i]=="O" and visited[0][i]==0: dfs(0,i) #last row for i in range(colSize): if board[rowSize-1][i]=="O" and visited[rowSize-1][i]==0: dfs(rowSize-1,i) #first coloumn for i in range(rowSize): if board[i][0]=="O" and visited[i][0]==0: dfs(i,0) #last coloumn for i in range(rowSize): if board[i][colSize-1]=="O" and visited[i][colSize-1]==0: dfs(i,colSize-1) #modify original array for i in range(rowSize): for j in range(colSize): if visited[i][j]!=1: board[i][j]="X"
surrounded-regions
python3 || easy || dfs solution
_soninirav
0
21
surrounded regions
130
0.361
Medium
1,578
https://leetcode.com/problems/surrounded-regions/discuss/2545751/Python-DFS-solution-with-explanation
class Solution: m, n = 0, 0 def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ self.m = len(board) self.n = len(board[0]) # check skipped first for i in range(self.m): if board[i][0] == "O": self.flip(i, 0, board) if board[i][-1] == "O": self.flip(i, self.n-1, board) for i in range(self.n): if board[0][i] == "O": self.flip(0, i, board) if board[-1][i] == "O": self.flip(self.m-1, i, board) for i in range(self.m): for j in range(self.n): if board[i][j] == "S": board[i][j] = "O" elif board[i][j] == "O": board[i][j] = "X" def flip(self, r, c, board) -> None: """ DFS Flip all O into X, avoid margin and connections """ board[r][c] = "S" for i, j in [[1, 0], [-1, 0], [0,1], [0,-1]]: if r + i not in range(self.m) or c + j not in range(self.n): continue if board[r+i][c+j] == "O": board[r+i][c+j] = "S" self.flip(r+i, c+j, board)
surrounded-regions
Python DFS solution with explanation
haoxj0122
0
20
surrounded regions
130
0.361
Medium
1,579
https://leetcode.com/problems/surrounded-regions/discuss/2497543/128-ms-or-99.7-faster-or-Python-or-DFS-or-Easy-to-Understand
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ rows, cols = len(board), len(board[0]) visited = set() def dfs(r, c): if ( r < 0 or r >= rows or c < 0 or c >= cols or (r, c) in visited or board[r][c] == 'X' ): return visited.add((r,c)) dfs(r+1, c) dfs(r-1, c) dfs(r, c+1) dfs(r, c-1) for c in range(cols): dfs(0, c) dfs(rows-1, c) for r in range(rows): dfs(r, 0) dfs(r, cols-1) for r in range(rows): for c in range(cols): if (r,c) not in visited: board[r][c] = 'X'
surrounded-regions
128 ms | 99.7% faster | Python | DFS | Easy to Understand
ronakpatel2198
0
81
surrounded regions
130
0.361
Medium
1,580
https://leetcode.com/problems/surrounded-regions/discuss/2437942/Surrounded-Regions-oror-Python3-oror-DFS
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]] # DFS on all 'O' from border and marking them as 'V' for i in range(0, len(board)): for j in range(0, len(board[0])): if(i == 0 or j == 0 or i == len(board)-1 or j == len(board[0])-1): if(board[i][j] == 'O'): self.dfs(i, j, board, dirs) # After dfs 'V' will be remained as original 'O' and all other 'O' which is not reachable from border will be converted to 'X' for i in range(0, len(board)): for j in range(0, len(board[0])): if(board[i][j] == 'V'): board[i][j] = 'O' elif(board[i][j] == 'O'): board[i][j] = 'X' return board def dfs(self, x, y, board, dirs): board[x][y] = 'V' for dx, dy in dirs: nx = x + dx ny = y + dy if(nx < 0 or ny < 0 or nx >= len(board) or ny >= len(board[0]) or board[nx][ny] != 'O'): continue self.dfs(nx, ny, board, dirs)
surrounded-regions
Surrounded Regions || Python3 || DFS
vanshika_2507
0
17
surrounded regions
130
0.361
Medium
1,581
https://leetcode.com/problems/surrounded-regions/discuss/2415830/Python-DFS-Understandable-solution
class Solution: def dfs(self,board,i,j): board[i][j]='y' for a,b in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)): if a>=len(board) or b>=len(board[0]) or a<0 or b<0: continue if board[a][b]=='O': self.dfs(board,a,b) def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ for i in range(len(board[0])): if board[0][i]=='O': self.dfs(board,0,i) for i in range(len(board)): if board[i][len(board[0])-1]=='O': self.dfs(board,i,len(board[0])-1) for i in range(len(board[0])): if board[len(board)-1][i]=='O': self.dfs(board,len(board)-1,i) for i in range(len(board)): if board[i][0]=='O': self.dfs(board,i,0) for i in range(len(board)): for j in range(len(board[0])): if board[i][j]=='O': board[i][j]='X' elif board[i][j]=='y': board[i][j]='O'
surrounded-regions
Python DFS Understandable solution
Neerajbirajdar
0
70
surrounded regions
130
0.361
Medium
1,582
https://leetcode.com/problems/surrounded-regions/discuss/2401508/130.-My-Python-and-JAVASolution-with-comments
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m, n = len(board), len(board[0]) # we only have to check the boundary, which means first row&amp;column, last row&amp;column. # If an O exists on the boundary, find every O connecting to it, # this region would be marked as F to claim that it would be uncahnged, (False to flip) # and "F" would be recoverd to O eventually for i in [0, m-1]: for j in range(n): # dfs function will find and process an entire O region self.dfs(board, i, j, m, n) for j in [0, n-1]: for i in range(m): self.dfs(board, i, j, m, n) for i in range(m): for j in range(n): if board[i][j]=='F': board[i][j]= 'O' elif board[i][j] == 'O': board[i][j] = 'X' return def dfs(self,board, i, j, m, n): # the condition: it has be in the board range, it has to be "O" # otherwise, we terminate this dfs if i<0 or i>m-1 or j<0 or j>n-1 or board[i][j]!='O': return board[i][j]='F' self.dfs(board, i+1, j, m, n) self.dfs(board, i-1, j, m, n) self.dfs(board, i, j+1, m, n) self.dfs(board, i, j-1, m, n) return
surrounded-regions
130. My Python and JAVASolution with comments
JunyiLin
0
19
surrounded regions
130
0.361
Medium
1,583
https://leetcode.com/problems/surrounded-regions/discuss/2121907/Python-or-Food-Fill-or-O(n-2)-Time-O(1)-Space
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) def traverse(i, j): if i < 0 or i >= m or j < 0 or j >= n: return if board[i][j] == "X": # don't need to change return if board[i][j] == "#": # mark boarder and its related O to "#" return board[i][j] = "#" # mark "O" to "#" traverse(i + 1, j) traverse(i - 1, j) traverse(i, j + 1) traverse(i, j - 1) for i in range(m): for j in range(n): edge = i == 0 or i == m - 1 or j == 0 or j == n - 1 if edge and board[i][j] == "O": traverse(i, j) # print(board) for i in range(m): for j in range(n): if board[i][j] == "O": board[i][j] = "X" if board[i][j] == "#": board[i][j] = "O"
surrounded-regions
Python | Food-Fill | O(n ^2) Time, O(1) Space
Kiyomi_
0
57
surrounded regions
130
0.361
Medium
1,584
https://leetcode.com/problems/surrounded-regions/discuss/2022556/Python-DFS-Solution-Explained
class Solution: def dfs(self, board, i, j): self.visited[i][j] = True for x, y in [(0,1),(1,0),(0,-1),(-1,0)]: ni = i + x nj = j + y if 0 <= ni < self.m and 0 <= nj < self.n: if (not self.visited[ni][nj]) and (board[ni][nj] == 'O'): self.dfs(board, ni, nj) def solve(self, board) -> None: """ Do not return anything, modify board in-place instead. """ self.m = len(board) self.n = len(board[0]) self.visited = [[False for j in range(self.n)] for i in range(self.m)] for i in range(self.m): if board[i][0] == 'O' and not self.visited[i][0]: self.dfs(board, i, 0) for i in range(self.m): if board[i][self.n-1] == 'O' and not self.visited[i][self.n-1]: self.dfs(board, i, self.n-1) for i in range(self.n): if board[0][i] == 'O' and not self.visited[0][i]: self.dfs(board, 0, i) for i in range(self.n): if board[self.m-1][i] == 'O' and not self.visited[self.m-1][i]: self.dfs(board, self.m-1, i) # Update non visited O's to X for i in range(self.m): for j in range(self.n): if board[i][j] == 'O' and not self.visited[i][j]: board[i][j] = 'X'
surrounded-regions
Python DFS Solution Explained
dbansal18
0
27
surrounded regions
130
0.361
Medium
1,585
https://leetcode.com/problems/surrounded-regions/discuss/2008137/Python-easy-to-read-and-understand-or-dfs
class Solution: def dfs(self, board, row, col): if row < 0 or col < 0 or row == len(board) or col == len(board[0]) or board[row][col] != 'O': return board[row][col] = 1 self.dfs(board, row-1, col) self.dfs(board, row, col-1) self.dfs(board, row+1, col) self.dfs(board, row, col+1) def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m, n = len(board), len(board[0]) for i in range(m): self.dfs(board, i, 0) self.dfs(board, i, n-1) for j in range(n): self.dfs(board, 0, j) self.dfs(board, m-1, j) for i in range(m): for j in range(n): if board[i][j] == 'O': board[i][j] = 'X' elif board[i][j] == 1: board[i][j] = 'O'
surrounded-regions
Python easy to read and understand | dfs
sanial2001
0
31
surrounded regions
130
0.361
Medium
1,586
https://leetcode.com/problems/surrounded-regions/discuss/1894413/DFS-Easy-Solution-In-Python
class Solution: def solve(self, board: List[List[str]]) -> None: row,col = len(board),len(board[0]) visited = set() def dfs(r,c): if (r,c) not in visited and 0<=r<row and 0<=c<col and board[r][c]=='O': visited.add((r,c)) board[r][c]='Y' dfs(r+1,c) dfs(r-1,c) dfs(r,c+1) dfs(r,c-1) return # For Border for c in range(col): dfs(0,c) dfs(row-1,c) for r in range(row): dfs(r,0) dfs(r,col-1) # For ( O -> X ) &amp; ( Y -> O ) for r in range(row): for c in range(col): Flag = True if board[r][c]=='Y': board[r][c]='O' Flag = False if board[r][c]=='O' and Flag: board[r][c]='X'
surrounded-regions
DFS Easy Solution In Python
gamitejpratapsingh998
0
109
surrounded regions
130
0.361
Medium
1,587
https://leetcode.com/problems/surrounded-regions/discuss/1851509/Python-or-BFS
class Solution: def solve(self, board: List[List[str]]) -> None: safeplace=set() r,c=len(board),len(board[0]) for i in range(r): if board[i][0]=='O': safeplace.add((i,0)) if board[i][c-1]=='O': safeplace.add((i,c-1)) for j in range(c): if board[0][j]=='O': safeplace.add((0,j)) if board[r-1][j]=='O': safeplace.add((r-1,j)) q=list(safeplace) neighbours=[(-1,0),(0,-1),(1,0),(0,1)] while q: i,j=q.pop(0) for a,b in neighbours: nx,ny=i+a,j+b if 0<=nx<r and 0<=ny<c and board[nx][ny]=='O' and (nx,ny) not in safeplace: q.append((nx,ny)) safeplace.add((nx,ny)) for i in range(r): for j in range(c): if board[i][j]=='O' and (i,j) not in safeplace: board[i][j]='X'
surrounded-regions
Python | BFS
heckt27
0
48
surrounded regions
130
0.361
Medium
1,588
https://leetcode.com/problems/surrounded-regions/discuss/1636261/Python-simple-solution%3A-start-from-boundaries!
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m, n = len(board), len(board[0]) if m <=2 or n <=2: return board # now let's assume m>=3 and n>=3 from collections import deque queue = deque([]) def valid(x, y): return x>=0 and x<=m-1 and y>=0 and y<=n-1 for i in range(0, m): if board[i][0] == "O": queue.append((i, 0)) if board[i][n-1] == "O": queue.append((i, n-1)) for j in range(0, n): if board[0][j] == "O": queue.append((0, j)) if board[m-1][j] == "O": queue.append((m-1, j)) while queue: x, y = queue.popleft() if board[x][y] == "O": # not captured yet board[x][y] = "N" if valid(x+1, y) and board[x+1][y] == "O": queue.append((x+1, y)) if valid(x-1, y) and board[x-1][y] == "O": queue.append((x-1, y)) if valid(x, y+1) and board[x][y+1] == "O": queue.append((x, y+1)) if valid(x, y-1) and board[x][y-1] == "O": queue.append((x, y-1)) else: # board[x][y] == "X" or "N" pass for i in range(m): for j in range(n): if board[i][j] == "O": board[i][j] = "X" elif board[i][j] == "N": board[i][j] = "O" return board
surrounded-regions
Python simple solution: start from boundaries!
byuns9334
0
83
surrounded regions
130
0.361
Medium
1,589
https://leetcode.com/problems/surrounded-regions/discuss/1623550/PYTHON-or-Solution-faster-then-bullet
class Solution: def dfs(self,board,i,j): if i<0 or j<0 or i>=len(board) or j>=len(board[0]): return elif board[i][j]=='X' or board[i][j]=='1': return elif board[i][j] == 'O': board[i][j] = '1' li = [(0,1),(1,0),(-1,0),(0,-1)] for n,m in li: self.dfs(board,i+n,j+m) def solve(self, graph: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ for i in range(len(graph)): self.dfs(graph,i,0) self.dfs(graph,i,len(graph[0])-1) for i in range(len(graph[0])): self.dfs(graph,0,i) self.dfs(graph,len(graph)-1,i) for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j]=='O': graph[i][j] = 'X' elif graph[i][j]=='1': graph[i][j] = 'O' return graph
surrounded-regions
PYTHON🐍 | Solution faster then bullet
Brillianttyagi
0
114
surrounded regions
130
0.361
Medium
1,590
https://leetcode.com/problems/surrounded-regions/discuss/1619543/Python-DFS
class Solution: def solve(self, board: List[List[str]])->None: def isSafe(i,j,grid,visited): if 0<=i<len(grid) and 0<=j<len(grid[0]) and visited[i][j]==False and grid[i][j]=='O': return True return False def travel(row,col,board,visited): visited[row][col]=True rowi = [0,1,0,-1] coli = [1,0,-1,0] for k in range(4): x = row+rowi[k] y = col+coli[k] if isSafe(x,y,board,visited): travel(x,y,board,visited) if len(board)<=2 or len(board[0])<=2: return board # we will traverse the boundry of the board and use dfs for each cell for adjacent neighbor # and use a visited matrix to save the visited positions visited = [[False for i in range(len(board[0]))] for j in range(len(board))] # i==0 for j in range(len(board[0])): if board[0][j]=='O': travel(0,j,board,visited) # j==0 for i in range(len(board)): if board[i][0]=='O': travel(i,0,board,visited) # i==len(board)-1 for j in range(len(board[0])): if board[len(board)-1][j]=='O': travel(len(board)-1,j,board,visited) # j = len(board[0])-1 for i in range(len(board)): if board[i][len(board[0])-1]=='O': travel(i,len(board[0])-1,board,visited) for i in range(1,len(board)-1): for j in range(1,len(board[0])-1): if visited[i][j]==False and board[i][j]=='O': board[i][j]='X' return board
surrounded-regions
Python DFS
Zach0787
0
86
surrounded regions
130
0.361
Medium
1,591
https://leetcode.com/problems/surrounded-regions/discuss/1610304/BFS-Python-3
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) for i in range(m): for j in range(n): visited = set() if board[i][j]=='O': bfs_arr = [(i,j)] visited.add((i,j)) surrounded = True while len(bfs_arr)>0: curr = bfs_arr.pop() if curr[0]==0 or curr[0]==m-1 or curr[1]==0 or curr[1]==n-1: surrounded = False for shift in [(+1,0),(-1,0),(0,+1),(0,-1)]: ind_i = curr[0]+shift[0] ind_j = curr[1] + shift[1] if ind_i>=0 and ind_i<m and ind_j>=0 and ind_j<n and board[ind_i][ind_j] == 'O' and (ind_i, ind_j) not in visited: bfs_arr.append((ind_i,ind_j )) visited.add((ind_i, ind_j)) for val in visited: if surrounded: board[val[0]][val[1]] = 'X'
surrounded-regions
BFS Python 3
throwawayleetcoder19843
0
51
surrounded regions
130
0.361
Medium
1,592
https://leetcode.com/problems/palindrome-partitioning/discuss/1667786/Python-Simple-Recursion-oror-Detailed-Explanation-oror-Easy-to-Understand
class Solution(object): @cache # the memory trick can save some time def partition(self, s): if not s: return [[]] ans = [] for i in range(1, len(s) + 1): if s[:i] == s[:i][::-1]: # prefix is a palindrome for suf in self.partition(s[i:]): # process suffix recursively ans.append([s[:i]] + suf) return ans
palindrome-partitioning
✅ [Python] Simple Recursion || Detailed Explanation || Easy to Understand
linfq
209
9,200
palindrome partitioning
131
0.626
Medium
1,593
https://leetcode.com/problems/palindrome-partitioning/discuss/1667786/Python-Simple-Recursion-oror-Detailed-Explanation-oror-Easy-to-Understand
class Solution(object): def __init__(self): self.memory = collections.defaultdict(list) def partition(self, s): if not s: return [[]] if s in self.memory: return self.memory[s] # the memory trick can save some time ans = [] for i in range(1, len(s) + 1): if s[:i] == s[:i][::-1]: # prefix is a palindrome for suf in self.partition(s[i:]): # process suffix recursively ans.append([s[:i]] + suf) self.memory[s] = ans return ans
palindrome-partitioning
✅ [Python] Simple Recursion || Detailed Explanation || Easy to Understand
linfq
209
9,200
palindrome partitioning
131
0.626
Medium
1,594
https://leetcode.com/problems/palindrome-partitioning/discuss/1667603/Python3-RECURSION-Explained
class Solution: def partition(self, s: str) -> List[List[str]]: l = len(s) def isPalindrom(s): return s == s[::-1] @cache def rec(start): if start == l: return [] res = [] for i in range(start + 1, l + 1): sub = s[start:i] if isPalindrom(sub): subres = rec(i) if not subres: res.append(deque([sub])) else: for arr in subres: copy = arr.copy() copy.appendleft(sub) res.append(copy) return res return rec(0)
palindrome-partitioning
❤ [Python3] RECURSION, Explained
artod
5
472
palindrome partitioning
131
0.626
Medium
1,595
https://leetcode.com/problems/palindrome-partitioning/discuss/2004437/Python-Bottom-up-DP-Solution-oror-100-Faster-oror-Iterative-oror-Easy-to-understand
class Solution: def partition(self, s: str) -> List[List[str]]: dp = [] n = len(s) for i in range(n+1): dp.append([]) # create dp of size n+1 dp[-1].append([]) # because for s[n:] i.e. empty string , answer = [[]] # dp[i] store all possible palindrome partitions of string s[i:] for i in range(n-1,-1,-1): for j in range(i+1,n+1): curr = s[i:j] # cosider each substring of s start from i-th character if curr == curr[::-1]: # if substring is palindrome # Consider first element of each partition is curr then add curr in the front of all partitions of string s[j:] , which are already stored in dp[j] for e in dp[j]: dp[i].append ([curr] + e) return dp[0] # All palindrome partitions of s[0:] = s
palindrome-partitioning
Python Bottom up DP Solution || 100% Faster || Iterative || Easy to understand
Laxman_Singh_Saini
3
154
palindrome partitioning
131
0.626
Medium
1,596
https://leetcode.com/problems/palindrome-partitioning/discuss/2263662/Easy-Python-Backtracking-Solution
class Solution: def partition(self, s: str) -> List[List[str]]: res, part = [], [] def dfs(i): if i >= len(s): res.append(part.copy()) return for j in range(i, len(s)): if isPali(s, i, j): part.append(s[i:j+1]) dfs(j + 1) part.pop() dfs(0) return res def isPali( s, l, r): while l < r: if s[l] != s[r]: return False l, r = l + 1, r - 1 return True
palindrome-partitioning
Easy Python Backtracking Solution
shikha_pandey
2
125
palindrome partitioning
131
0.626
Medium
1,597
https://leetcode.com/problems/palindrome-partitioning/discuss/1669234/Python-Full-Code-Explanation-or-Backtracking
class Solution: def partition(self, s: str) -> List[List[str]]: result = [] # will store all posible partitions partition = [] # current partition # function for backtracking def dfs(i): # i is the index of the character we are currently at if i >= len(s): # checking base case result.append(partition.copy()) ''' because there is only 1 partition variable and we will keep updating/changing it so we need to copy it everytime we append to result ''' return for j in range(i,len(s)): # generating every single possible substring if self.isPalindrome(s,i,j): # checking is the substring is palindrome partition.append(s[i:j+1]) dfs(j + 1) # recursively continue our dfs partition.pop() # if a substring is not a palindrome, we just skip it dfs(0) return result # function for palindrome checking def isPalindrome(self,s,left,right): while left < right: if s[left] != s[right]: # if character at left position doesnot equal character at left position return False # substring is not palindrom left,right = left+1,right-1 # if they are equal we update left and right pointers return True # substring is palindrome
palindrome-partitioning
Python Full Code Explanation | Backtracking
yashitanamdeo
2
311
palindrome partitioning
131
0.626
Medium
1,598
https://leetcode.com/problems/palindrome-partitioning/discuss/1668647/Python3-backtracking-solution
class Solution: def partition(self, s: str) -> List[List[str]]: substring = [] result = [] # backtracking def dfs(i): if i >= len(s): result.append(substring.copy()) return for j in range(i, len(s)): if self.check_palindrome(s, i, j): substring.append(s[i:j+1]) dfs(j+1) substring.pop() dfs(0) return result # check if it is palindrome def check_palindrome(self, s, l, r): while l < r: if s[l] == s[r]: l += 1 r -= 1 else: return False return True
palindrome-partitioning
Python3 backtracking solution
Janetcxy
2
75
palindrome partitioning
131
0.626
Medium
1,599