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/build-array-from-permutation/discuss/2717909/Python-One-liner-solution.
class Solution: def buildArray(self, nums: List[int]) -> List[int]: n=len(nums) for i in range(len(nums)): nums.append(nums[nums[i]]) return nums[n:]
build-array-from-permutation
Python One liner solution.
guneet100
0
5
build array from permutation
1,920
0.912
Easy
27,100
https://leetcode.com/problems/build-array-from-permutation/discuss/2706250/Easiest-Python-Brute-force-solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: nums2 = [] for i in nums: nums2.append(i) for i in range(0,len(nums)): nums2[i] = nums[nums[i]] return nums2
build-array-from-permutation
Easiest Python - Brute force solution
jaiswaldevansh27
0
6
build array from permutation
1,920
0.912
Easy
27,101
https://leetcode.com/problems/build-array-from-permutation/discuss/2666324/Python-or-list-comprehensions
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[num] for num in nums]
build-array-from-permutation
Python | list comprehensions
user9015KF
0
3
build array from permutation
1,920
0.912
Easy
27,102
https://leetcode.com/problems/build-array-from-permutation/discuss/2652590/Simple-Python-Solution-beats-98.1
class Solution: def buildArray(self, nums: List[int]) -> List[int]: result = [] for i in range(len(nums)): result.append(nums[nums[i]]) return result
build-array-from-permutation
Simple Python Solution beats 98.1%
shubhamshinde245
0
7
build array from permutation
1,920
0.912
Easy
27,103
https://leetcode.com/problems/build-array-from-permutation/discuss/2651079/Python-3-Easy-Solution-Using-For-loop
class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans = [] for i in range(len(nums)): ans.append(nums[nums[i]]) return ans
build-array-from-permutation
Python 3 Easy Solution Using For loop
Maazkhattak
0
2
build array from permutation
1,920
0.912
Easy
27,104
https://leetcode.com/problems/build-array-from-permutation/discuss/2515118/Python-Solution-easy
class Solution(object): def buildArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ ans = [] for i in range(len(nums)): ans.append(nums[nums[i]]) return ans
build-array-from-permutation
Python Solution easy
savvy_phukan
0
81
build array from permutation
1,920
0.912
Easy
27,105
https://leetcode.com/problems/build-array-from-permutation/discuss/2481643/One-liner-faster-than-96
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[nums[i]] for i in range(len(nums))]
build-array-from-permutation
One liner faster than 96%
rockdtaz
0
76
build array from permutation
1,920
0.912
Easy
27,106
https://leetcode.com/problems/build-array-from-permutation/discuss/2468784/Python-3-or-List-Comprehension-or-Easy-to-Understand-(With-Reference)
class Solution: def buildArray(self, nums: List[int]) -> List[int]: nums2 = [nums[i] for i in nums] return nums2
build-array-from-permutation
Python 3 | List Comprehension | Easy to Understand (With Reference)
danny42
0
62
build array from permutation
1,920
0.912
Easy
27,107
https://leetcode.com/problems/build-array-from-permutation/discuss/2398508/Simple-python-code
class Solution: def buildArray(self, nums: List[int]) -> List[int]: #create an empty list ans = [] #iterate through the list (nums) for i in range(len(nums)): #add the nums[nums[i]] to ans-> list ans.append(nums[nums[i]]) #return ans-> list return ans
build-array-from-permutation
Simple python code
thomanani
0
154
build array from permutation
1,920
0.912
Easy
27,108
https://leetcode.com/problems/build-array-from-permutation/discuss/2398508/Simple-python-code
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[i] for i in nums]
build-array-from-permutation
Simple python code
thomanani
0
154
build array from permutation
1,920
0.912
Easy
27,109
https://leetcode.com/problems/build-array-from-permutation/discuss/2373092/Easy-solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: a=[] for i,v in enumerate(nums): a.append(nums[nums[i]]) return a
build-array-from-permutation
Easy solution
ksn7
0
87
build array from permutation
1,920
0.912
Easy
27,110
https://leetcode.com/problems/build-array-from-permutation/discuss/2275343/Python-Solution-using-List-Comprehension
class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans=[nums[nums[i]] for i in range(len(nums))] return ans
build-array-from-permutation
Python Solution using List Comprehension
diptaraj23
0
72
build array from permutation
1,920
0.912
Easy
27,111
https://leetcode.com/problems/build-array-from-permutation/discuss/2259354/Python-one-liner-and-long-code
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[x] for x in nums] def buildArrayLongCode(self, nums: List[int]) -> List[int]: ans = [] for i in range(len(nums)): ans.append(nums[nums[i]]) return ans
build-array-from-permutation
Python one liner and long code
user9702g
0
49
build array from permutation
1,920
0.912
Easy
27,112
https://leetcode.com/problems/build-array-from-permutation/discuss/2248431/simplest-python-solution-using-list.insert(indexelement)-and-enumerate
class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans=[] for index,value in enumerate(nums): ans.insert(index,nums[value]) return ans
build-array-from-permutation
simplest python solution using list.insert(index,element) and enumerate
dalersingh13121998
0
89
build array from permutation
1,920
0.912
Easy
27,113
https://leetcode.com/problems/build-array-from-permutation/discuss/2115969/Python-Easy-solutions-with-complexities
class Solution: def buildArray(self, nums: List[int]) -> List[int]: answer = [] for i in range(len(nums)): answer.append(nums[nums[i]]) return answer # space O(N) # time O(N)
build-array-from-permutation
[Python] Easy solutions with complexities
mananiac
0
167
build array from permutation
1,920
0.912
Easy
27,114
https://leetcode.com/problems/build-array-from-permutation/discuss/2115969/Python-Easy-solutions-with-complexities
class Solution: def buildArray(self,nums: List[int]) -> List[int]: q = len(nums) for i in range(len(nums)): #a = qb + r r = nums[i] b = nums[nums[i]] % q nums[i] = q*b + r for i in range(len(nums)): nums[i] = nums[i] // q return nums # space O(1) # time O(N)
build-array-from-permutation
[Python] Easy solutions with complexities
mananiac
0
167
build array from permutation
1,920
0.912
Easy
27,115
https://leetcode.com/problems/build-array-from-permutation/discuss/2101241/easy-understanding-or-python-or-short-or-simply-ans-or-clean-code
class Solution: def buildArray(self, nums: List[int]) -> List[int]: l=[] for i in range(len(nums)): l.append(nums[nums[i]]) return l
build-array-from-permutation
easy understanding | python | short | simply ans | clean code
T1n1_B0x1
0
107
build array from permutation
1,920
0.912
Easy
27,116
https://leetcode.com/problems/build-array-from-permutation/discuss/1959381/Python-3-Solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans = [0] * len(nums) for i in range(len(nums)): ans[i] = nums[nums[i]] return ans
build-array-from-permutation
Python 3 Solution
AprDev2011
0
99
build array from permutation
1,920
0.912
Easy
27,117
https://leetcode.com/problems/build-array-from-permutation/discuss/1959381/Python-3-Solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: n = len(nums) for i in range(n): nums[i] = n * (nums[nums[i]] % n) + nums[i] for i in range(n): nums[i] = nums[i] // n return nums
build-array-from-permutation
Python 3 Solution
AprDev2011
0
99
build array from permutation
1,920
0.912
Easy
27,118
https://leetcode.com/problems/build-array-from-permutation/discuss/1934290/Memory-Usage-less-than-91.65-of-Python3-submissions
class Solution: def buildArray(self, nums: List[int]) -> List[int]: new_arr = [] for x in nums: new_arr.append(nums[x]) return new_arr
build-array-from-permutation
Memory Usage less than 91.65% of Python3 submissions
ruhiddin_uzb
0
106
build array from permutation
1,920
0.912
Easy
27,119
https://leetcode.com/problems/build-array-from-permutation/discuss/1928369/Python3-One-Line-Solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[nums[i]] for i in range(len(nums))]
build-array-from-permutation
[Python3] One-Line Solution
terrencetang
0
73
build array from permutation
1,920
0.912
Easy
27,120
https://leetcode.com/problems/build-array-from-permutation/discuss/1902326/Python-One-Liner!-x2
class Solution: def buildArray(self, nums): return [nums[i] for i in nums]
build-array-from-permutation
Python - One Liner! x2
domthedeveloper
0
122
build array from permutation
1,920
0.912
Easy
27,121
https://leetcode.com/problems/build-array-from-permutation/discuss/1902326/Python-One-Liner!-x2
class Solution: def buildArray(self, nums): return map(lambda x:nums[x], nums)
build-array-from-permutation
Python - One Liner! x2
domthedeveloper
0
122
build array from permutation
1,920
0.912
Easy
27,122
https://leetcode.com/problems/build-array-from-permutation/discuss/1885405/Python-one-liner
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[x] for x in nums]
build-array-from-permutation
Python one liner
khayaltech
0
89
build array from permutation
1,920
0.912
Easy
27,123
https://leetcode.com/problems/build-array-from-permutation/discuss/1861056/Python-One-Liner
class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [ nums[number] for number in nums]
build-array-from-permutation
Python One Liner
hardik097
0
102
build array from permutation
1,920
0.912
Easy
27,124
https://leetcode.com/problems/build-array-from-permutation/discuss/1821442/3-Lines-Python-Solution-oror-60-Faster-oror-Memory-less-than-96
class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans = [None]*len(nums) for i in range(len(nums)): ans[i]=nums[nums[i]] return ans
build-array-from-permutation
3-Lines Python Solution || 60% Faster || Memory less than 96%
Taha-C
0
82
build array from permutation
1,920
0.912
Easy
27,125
https://leetcode.com/problems/build-array-from-permutation/discuss/1787138/Python3-recursive-NoForLoops-allowed
class Solution: def buildArray(self, nums: List[int]) -> List[int]: answer = [] def noForLoops(index): if len(answer) >= len(nums): return answer.append(nums[nums[index]]) index += 1 noForLoops(index) noForLoops(0) return answer
build-array-from-permutation
Python3 recursive NoForLoops allowed
user5571e
0
86
build array from permutation
1,920
0.912
Easy
27,126
https://leetcode.com/problems/build-array-from-permutation/discuss/1434015/Python-3-easy-solution
class Solution: def buildArray(self, nums: List[int]) -> List[int]: x=[nums[nums[i]] for i in range(0,len(nums))] return x;
build-array-from-permutation
Python 3 easy solution
Pranav447
0
331
build array from permutation
1,920
0.912
Easy
27,127
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314370/Python3-3-line
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: for i, t in enumerate(sorted((d+s-1)//s for d, s in zip(dist, speed))): if i == t: return i return len(dist)
eliminate-maximum-number-of-monsters
[Python3] 3-line
ye15
4
312
eliminate maximum number of monsters
1,921
0.379
Medium
27,128
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314362/Python-oror-easy-comparator-sort
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: def help(a): return a[0]/a[1] temp = [] for i in range(len(dist)): temp.append([dist[i],speed[i]]) temp = sorted(temp,key = help) ans = 0 i = 0 while i<len(temp): if (temp[i][0] - (temp[i][1])*i) > 0 : ans += 1 i += 1 else: break return ans
eliminate-maximum-number-of-monsters
Python || easy comparator sort
harshhx
3
243
eliminate maximum number of monsters
1,921
0.379
Medium
27,129
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314327/python-easy-solutionoror-sorting-arrival-time
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: if 0 in set(dist): return 0 ans=[] for i,el in enumerate(dist): t=math.ceil(el/speed[i]) ans.append(t) ans.sort() count=0 prev=0 print(ans) for i in range(len(ans)): if prev==ans[i]: return count else : count+=1 prev+=1 return count ```
eliminate-maximum-number-of-monsters
python easy solution|| sorting arrival time🐍🐍
aayush_chhabra
3
260
eliminate maximum number of monsters
1,921
0.379
Medium
27,130
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1366809/Sort-arrival-times-98-speed
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: for i, t in enumerate(sorted(d / s for d, s in zip(dist, speed))): if t <= i: return i return len(dist)
eliminate-maximum-number-of-monsters
Sort arrival times, 98% speed
EvgenySH
1
138
eliminate maximum number of monsters
1,921
0.379
Medium
27,131
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/2662158/Python-3-simple-solution.
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: time = [math.ceil(x / y) for x, y in zip(dist, speed)] time.sort() res = 1 for i in range(1, len(time)): if time[i] <= res: return res res += 1 return res
eliminate-maximum-number-of-monsters
Python 3 simple solution.
MaverickEyedea
0
5
eliminate maximum number of monsters
1,921
0.379
Medium
27,132
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/2513240/Heap-solution
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: from heapq import heappush, heappop import math if len(dist) == 1: return 1 time = [math.ceil(dist[i]/speed[i]) for i in range(len(dist))] heapify(time) ans = 0 i = 0 while time: i+=1 if heappop(time)-i>=0: ans+=1 else: break return ans
eliminate-maximum-number-of-monsters
Heap solution
hacktheirlives
0
20
eliminate maximum number of monsters
1,921
0.379
Medium
27,133
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/2115996/python-3-oror-simple-greedy-solution
class Solution: def eliminateMaximum(self, dists: List[int], speeds: List[int]) -> int: times = sorted(dist / speed for dist, speed in zip(dists, speeds)) for i, time in enumerate(times): if i >= time: return i return len(times)
eliminate-maximum-number-of-monsters
python 3 || simple greedy solution
dereky4
0
61
eliminate maximum number of monsters
1,921
0.379
Medium
27,134
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314969/calculate-times-and-sort-by-arrival
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: n=len(dist) t=[] for i in range(n): t.append((dist[i]/speed[i])) t.sort() for i in range(n): # current time is i and monster arrival time is t[i] if current time is greater than or equal to monster arrival time GAME OVER !!! if(i>=t[i]): i=i-1 break return i+1
eliminate-maximum-number-of-monsters
calculate times and sort by arrival
madhukar0011
0
23
eliminate maximum number of monsters
1,921
0.379
Medium
27,135
https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314579/Well-Explained-ororSimple-Code-oror-4-Lines-oror-98-faster-oror-Easily-Understantable
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: time = [d/s for d,s in zip(dist,speed)] time.sort() c=0 for i,t in enumerate(time): if i<t: c+=1 else: break return c
eliminate-maximum-number-of-monsters
📌Well-Explained ||Simple Code || 4 Lines || 98% faster || Easily-Understantable 🐍
abhi9Rai
0
43
eliminate maximum number of monsters
1,921
0.379
Medium
27,136
https://leetcode.com/problems/count-good-numbers/discuss/1314484/Python3-Powermod-hack-3-lines
class Solution: def countGoodNumbers(self, n: int) -> int: ''' ans=1 MOD=int(10**9+7) for i in range(n): if i%2==0: ans*=5 else: ans*=4 ans%=MOD return ans ''' MOD=int(10**9+7) fives,fours=n//2+n%2,n//2 # 5^fives*4^fours % MOD # = 5^fives % MOD * 4^fours % MOD return (pow(5,fives,MOD) * pow(4,fours,MOD)) % MOD
count-good-numbers
[Python3] Powermod hack, 3 lines
mikeyliu
5
396
count good numbers
1,922
0.384
Medium
27,137
https://leetcode.com/problems/count-good-numbers/discuss/1314522/Well-explained-oror-4-Lines-oror-97-faster-oror-easily-understandable
class Solution: def countGoodNumbers(self, n: int) -> int: MOD = 10**9+7 # No. of even places if n%2==0: ne=n//2 else: ne=(n+1)//2 # No. of odd places no=n//2 te = pow(5,ne,MOD) #Total number of even places combinations. tp = pow(4,no,MOD) #Total number of odd/prime combinations. return (tp*te)%MOD
count-good-numbers
📌 Well-explained || 4 Lines || 97% faster || easily-understandable 🐍
abhi9Rai
4
290
count good numbers
1,922
0.384
Medium
27,138
https://leetcode.com/problems/count-good-numbers/discuss/1314377/Python3-1-line
class Solution: def countGoodNumbers(self, n: int) -> int: return pow(5, (n+1)//2, 1_000_000_007) * pow(4, n//2, 1_000_000_007) % 1_000_000_007
count-good-numbers
[Python3] 1-line
ye15
1
125
count good numbers
1,922
0.384
Medium
27,139
https://leetcode.com/problems/count-good-numbers/discuss/2781412/Fastest-Python-Solution
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1 if n==1: return x if n<0: n = -1 * n return 1/(self.myPow(x,n)) elif n%2 == 0: halfvalue = self.myPow(x,n//2) return halfvalue * halfvalue else: oddhalfvalue = self.myPow(x,(n-1)//2) return oddhalfvalue * oddhalfvalue * x def countGoodNumbers(self, n: int) -> int: MOD = 10**9 + 7 primes = 4 evens = 5 ans = 1 if n%2 == 0: odd_indexes = even_indexes = n//2 else: odd_indexes = n//2 even_indexes = odd_indexes + 1 ans1 = (pow(primes,odd_indexes,1_000_000_007)) % MOD ans2 = (pow(evens,even_indexes,1_000_000_007)) % MOD ans = (ans1 * ans2) % MOD return int(ans)
count-good-numbers
Fastest Python Solution
aayushjain001
0
6
count good numbers
1,922
0.384
Medium
27,140
https://leetcode.com/problems/count-good-numbers/discuss/2748732/Python-or-Fast-Exponentation
class Solution: def countGoodNumbers(self, n: int) -> int: p = 10**9 + 7 if n % 2 == 0: return pow(20, n // 2, p) else: return (5 * pow(20, (n-1) // 2, p)) % p
count-good-numbers
Python | Fast Exponentation
on_danse_encore_on_rit_encore
0
8
count good numbers
1,922
0.384
Medium
27,141
https://leetcode.com/problems/count-good-numbers/discuss/1777792/Python3-Concise
class Solution: def countGoodNumbers(self, n: int) -> int: fours = n // 2 fives = (n + 1) // 2 mod = 10**9 + 7 ans = pow(4, fours, mod) * pow(5, fives, mod) return ans % mod
count-good-numbers
Python3 Concise
shtanriverdi
0
148
count good numbers
1,922
0.384
Medium
27,142
https://leetcode.com/problems/count-good-numbers/discuss/1408117/python-O(logn)-using-5n2-at-even-indexes-and-4n2-at-odd-indices-75-faster-runtime
class Solution: def countGoodNumbers(self, n: int) -> int: # Reusing the super power logic # to calculate pow(x,n)%mod def myPow(x: int, n: int, mod: int) -> int: if n == 0: return 1 elif n == 1: return x else: half = myPow(x, n//2,mod) if n % 2 == 0: # Eg: n = 4 we can split into 2 and 2 # so we multiply two halves alone return (half*half)%mod # Eg: n = 5 we get n//2 = 2 # which we can split into 2,2,1 # so we multiply the halves twice and multiply the x for once return ((half*half)%mod*x)%mod # For an odd length string we get n//2+1 odd indices and n//2 even indices # For an even length string we get n//2 odd indices and n//2 even indices if n%2 == 0: return ((myPow(4,n//2,10**9+7))*(myPow(5,n//2,10**9+7)))%(10**9+7) return ((myPow(4,n//2,10**9+7))*(myPow(5,1+n//2,10**9+7)))%(10**9+7)
count-good-numbers
[python] O(logn) using 5^n//2 at even indexes and 4^n//2 at odd indices - 75 % faster runtime
Hariharan-SV
0
238
count good numbers
1,922
0.384
Medium
27,143
https://leetcode.com/problems/count-good-numbers/discuss/1366913/Built-in-pow()-with-mod-as-argument-98-speed
class Solution: def countGoodNumbers(self, n: int) -> int: odds = n // 2 return (pow(5, n - odds, 1_000_000_007) * pow(4, odds, 1_000_000_007) % 1_000_000_007)
count-good-numbers
Built-in pow() with mod as argument, 98% speed
EvgenySH
0
164
count good numbers
1,922
0.384
Medium
27,144
https://leetcode.com/problems/count-square-sum-triples/discuss/2318104/Easy-Solution-oror-PYTHON
```class Solution: def countTriples(self, n: int) -> int: count = 0 sqrt = 0 for i in range(1,n-1): for j in range(i+1, n): sqrt = ((i*i) + (j*j)) ** 0.5 if sqrt % 1 == 0 and sqrt <= n: count += 2 return (count) *Please Upvote if you like*
count-square-sum-triples
Easy Solution || PYTHON
Jonny69
2
134
count square sum triples
1,925
0.68
Easy
27,145
https://leetcode.com/problems/count-square-sum-triples/discuss/1336127/Python3-enumeration
class Solution: def countTriples(self, n: int) -> int: ans = 0 for a in range(1, n): for b in range(a+1, n): c = int(sqrt(a*a + b*b)) if a*a + b*b == c*c and c <= n: ans += 2 return ans
count-square-sum-triples
[Python3] enumeration
ye15
1
125
count square sum triples
1,925
0.68
Easy
27,146
https://leetcode.com/problems/count-square-sum-triples/discuss/1331860/Easy-Python3-faster-than-100
class Solution: def countTriples(self, n: int) -> int: ans=0 for i in range(1,n): for j in range(1,n): c= (i**2+j**2)**0.5 if c.is_integer() and c<=n: ans+=1 return ans
count-square-sum-triples
Easy Python3 faster than 100%
svr300
1
153
count square sum triples
1,925
0.68
Easy
27,147
https://leetcode.com/problems/count-square-sum-triples/discuss/2582971/Python3-oror-O(N*N)-optimized-solution
class Solution: def countTriples(self, n: int) -> int: dt = defaultdict(lambda:0) res = 0 for i in range(n+1): dt[i*i] = i for i in range(1,n-1): for j in range(i+1,n): if dt[(i*i)+(j*j)]: res+=2 return res
count-square-sum-triples
Python3 || O(N*N) optimized solution
shacid
0
10
count square sum triples
1,925
0.68
Easy
27,148
https://leetcode.com/problems/count-square-sum-triples/discuss/2575802/solving-using-binary-search
class Solution: def isSquare(self, target, n): i, j = 1,n while i <= j: mid = (i+j)//2 s = mid*mid # print(i,j, mid, s) if s == target: return True elif s < target: i = mid + 1 else: j = mid - 1 return False def countTriples(self, n: int) -> int: ans = 0 for i in range(1, n+1): for j in range(1, n+1): cond = self.isSquare(i*i + j*j, n) if cond: ans += 1 # print(i,j) return ans
count-square-sum-triples
solving using binary search
tejtharun625
0
23
count square sum triples
1,925
0.68
Easy
27,149
https://leetcode.com/problems/count-square-sum-triples/discuss/2188619/Python-simple-solution
class Solution: def countTriples(self, n: int) -> int: ans = 0 for i in range(1,n+1): for j in range(1,n+1): if ((i**2 + j**2)**0.5) == int((i**2 + j**2)**0.5) and int((i**2 + j**2)**0.5) <= n: ans += 1 return ans
count-square-sum-triples
Python simple solution
StikS32
0
103
count square sum triples
1,925
0.68
Easy
27,150
https://leetcode.com/problems/count-square-sum-triples/discuss/1983732/Python3-90-faster-with-explanation
class Solution: def countTriples(self, n: int) -> int: numlist, mapper, counter = [], {}, 0 for i in range(1, n + 1): numlist.append(i * i) mapper[i *i] = 1 for i in range(len(numlist)): j = i + 1 while j < len(numlist): if numlist[i] + numlist[j] in mapper: counter += 1 # print(numlist[i], numlist[j]) j += 1 #print(mapper, numlist) return counter * 2
count-square-sum-triples
Python3, 90% faster with explanation
cvelazquez322
0
262
count square sum triples
1,925
0.68
Easy
27,151
https://leetcode.com/problems/count-square-sum-triples/discuss/1905338/Python-easy-solution-for-beginners
class Solution: def countTriples(self, n: int) -> int: count = 0 for i in range(1, n+1): for j in range(i+1, n+1): if math.sqrt((i * i) + (j * j)) <= n and int(math.sqrt((i * i) + (j * j))) == math.sqrt((i * i) + (j * j)): count += 2 return count
count-square-sum-triples
Python easy solution for beginners
alishak1999
0
142
count square sum triples
1,925
0.68
Easy
27,152
https://leetcode.com/problems/count-square-sum-triples/discuss/1845506/6-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-100
class Solution: def countTriples(self, n: int) -> int: ans=0 for i in range(1,n+1): for j in range(1,i): k=sqrt(i**2+j**2) if int(k)==k and k<=n: ans+=2 return ans
count-square-sum-triples
6-Lines Python Solution || 50% Faster || Memory less than 100%
Taha-C
0
126
count square sum triples
1,925
0.68
Easy
27,153
https://leetcode.com/problems/count-square-sum-triples/discuss/1845506/6-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-100
class Solution: def countTriples(self, n: int) -> int: ans=0 ; S=set() for i in range(1,n+1): S.add(i**2) for i in range(1,n+1): for j in range(i+1,n+1): if i**2+j**2 in S: ans+=2 return ans
count-square-sum-triples
6-Lines Python Solution || 50% Faster || Memory less than 100%
Taha-C
0
126
count square sum triples
1,925
0.68
Easy
27,154
https://leetcode.com/problems/count-square-sum-triples/discuss/1541994/Precompute-squares-87-speed
class Solution: squares = [i * i for i in range(1, 251)] def countTriples(self, n: int) -> int: upper_idx = bisect_right(Solution.squares, n * n) set_upper = set(Solution.squares[:upper_idx]) count = 0 for i in range(upper_idx - 1): for j in range(i + 1, upper_idx): if Solution.squares[i] + Solution.squares[j] in set_upper: count += 2 return count
count-square-sum-triples
Precompute squares, 87% speed
EvgenySH
0
116
count square sum triples
1,925
0.68
Easy
27,155
https://leetcode.com/problems/count-square-sum-triples/discuss/1329201/Python-solution-using-memoization-below-500-ms-runtime
class Solution: cache = {1:0, 2:0, 3:0, 4:0} def countTriples(self, n: int) -> int: if n in self.cache.keys(): return self.cache[n] else: self.cache[n] = self.findTriples(n) + self.countTriples(n-1) return self.cache[n] def findTriples(self, n: int) -> int: count = 0 for a in range(0, n): for b in range(a, n): if self.isSquareTriple(a, b, n): count += 1 return count*2 def isSquareTriple(self, a: int, b: int, c: int) -> bool: if ((a*a) + (b*b) == (c*c)): return True else: return False
count-square-sum-triples
Python solution using memoization, below 500 ms runtime
njain07
0
134
count square sum triples
1,925
0.68
Easy
27,156
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1329534/Python-3-or-BFS-Deque-In-place-or-Explanation
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: q = collections.deque([(*entrance, 0)]) m, n = len(maze), len(maze[0]) maze[entrance[0]][entrance[1]] == '+' while q: x, y, c = q.popleft() if (x == 0 or x == m-1 or y == 0 or y == n-1) and [x, y] != entrance: return c for i, j in [(x+_x, y+_y) for _x, _y in [(-1, 0), (1, 0), (0, -1), (0, 1)]]: if 0 <= i < m and 0 <= j < n and maze[i][j] == '.': maze[i][j] = '+' q.append((i, j, c + 1)) return -1
nearest-exit-from-entrance-in-maze
Python 3 | BFS, Deque, In-place | Explanation
idontknoooo
5
197
nearest exit from entrance in maze
1,926
0.49
Medium
27,157
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2713932/Fastest-Python-BFS-solution
class Solution: def nearestExit(self, grid: List[List[str]], entrance: List[int]) -> int: m=len(grid) n=len(grid[0]) lst=[[entrance[0],entrance[1],0]] visited=[[-1]*n for i in range(m)] row=[-1,1,0,0] col=[0,0,-1,1] visited[entrance[0]][entrance[1]]=1 while lst: x,y,d=lst.pop(0) for i in range(4): if x+row[i]>=0 and x+row[i]<m and y+col[i]>=0 and y+col[i]<n and visited[x+row[i]][y+col[i]]==-1 and grid[x+row[i]][y+col[i]]=='.': if x+row[i]==0 or x+row[i]==m-1 or y+col[i]==0 or y+col[i]==n-1: return d+1 lst.append([x+row[i],y+col[i],d+1]) visited[x+row[i]][y+col[i]]=1 return -1
nearest-exit-from-entrance-in-maze
Fastest, Python BFS solution
beneath_ocean
4
270
nearest exit from entrance in maze
1,926
0.49
Medium
27,158
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1343637/WEEB-DOES-BFS-PYTHON
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: row, col = len(maze), len(maze[0]) visited, steps = set([]), 0 queue = deque([entrance]) answer = set([(0,y) for y in range(0,col) if maze[0][y] == "."] + [(row-1,y) for y in range(0,col) if maze[row-1][y] == "."] + [(x,0) for x in range(1,row-1) if maze[x][0] == "."] + [(x,col-1) for x in range(1,row-1) if maze[x][col-1] == "."]) while queue: for _ in range(len(queue)): x, y = queue.popleft() if (x,y) in visited: continue visited.add((x,y)) 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 maze[nx][ny] == ".": if (nx,ny) in answer and (nx,ny) not in visited: return steps+1 queue.append((nx,ny)) steps+=1 return -1
nearest-exit-from-entrance-in-maze
WEEB DOES BFS PYTHON
Skywalker5423
2
123
nearest exit from entrance in maze
1,926
0.49
Medium
27,159
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2837306/Python-BFS-Easy-with-comments
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: # BFS rows, cols = len(maze), len(maze[0]) # Set visited spaces to "+" maze[entrance[0]][entrance[1]] = '+' # Process stops in a queue queue = collections.deque() # Add first stop in queue queue.appendleft([entrance[0],entrance[1],0]) # Iterate until queue empty or we reach an exit while queue: row, col, steps = queue.pop() # Check each direction breadth first for r, c in [[row+1, col], [row-1, col], [row, col+1], [row, col-1]]: # Check in bounds and it not a wall if 0 <= r < rows and 0 <= c < cols and maze[r][c] == '.': # Check for exit if (r == 0) or (c == 0) or (r == rows - 1) or (c == cols -1): return steps+1 # Add stop to visited maze[r][c] = '+' # BFS, new stops get added at the end of the queue, not the front queue.appendleft([r,c,steps+1]) # No exit found return -1
nearest-exit-from-entrance-in-maze
😃 Python BFS Easy with comments
drblessing
1
25
nearest exit from entrance in maze
1,926
0.49
Medium
27,160
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835192/python-solution
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows=len(maze) cols=len(maze[0]) sx,sy=entrance maze[sx][sy]='s' for x in range(rows): if maze[x][0]=='.': maze[x][0]='e' if maze[x][-1]=='.': maze[x][-1]='e' for y in range(cols): if maze[0][y]=='.': maze[0][y]='e' if maze[-1][y]=='.': maze[-1][y]='e' dir=[(0,1),(1,0),(-1,0),(0,-1)] done=[[False]*cols for _ in range(rows)] queue=collections.deque() queue.append((0,sx,sy)) done[sx][sy]=True while len(queue)>0: d,x,y=queue.popleft() for dx,dy in dir: nx,ny=x+dx,y+dy if 0<=nx<rows and 0<=ny < cols and not done[nx][ny]: if maze[nx][ny]==".": queue.append((d+1,nx,ny)) elif maze[nx][ny] =="e": return d+1 return -1 # [6] BFS failed, there is no escape
nearest-exit-from-entrance-in-maze
python solution
ashishneo
1
55
nearest exit from entrance in maze
1,926
0.49
Medium
27,161
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2288054/Python3-BFS-similar-to-shortest-path-in-Binary-matrix
class Solution: def nearestExit(self, grid: List[List[str]], entrance: List[int]) -> int: m,n,visited,queue = len(grid), len(grid[0]), {}, [(entrance[0],entrance[1],0)] while queue: i,j,distance = queue.pop(0) k = visited.get((i,j)) if(k == None or k > distance): visited[(i,j)] = distance for x,y in [(0,-1),(0,1),(-1,0),(1,0)]: newI, newJ = i+x, j+y if(newI >= 0 and newI < m and newJ >= 0 and newJ < n and grid[newI][newJ] != "+"): queue.append((newI, newJ, distance + 1)) result = float("inf") for i in [0,m-1]: for j in range(n): k = visited.get((i,j)) if k != None and [i,j] != entrance: result = min(result, k) for j in [0, n-1]: for i in range(m): k = visited.get((i,j)) if k != None and [i,j] != entrance: result = min(result, k) return -1 if result == float("inf") else result
nearest-exit-from-entrance-in-maze
📌 Python3 BFS similar to shortest path in Binary matrix
Dark_wolf_jss
1
40
nearest exit from entrance in maze
1,926
0.49
Medium
27,162
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2845537/Clean-BFS-in-Python-3
class Solution: def nearestExit(self, M: List[List[str]], entrance: List[int]) -> int: from math import inf from collections import deque m, n = len(M), len(M[0]) q = deque([(tuple(entrance), 0)]) d = ((0, 1), (0, -1), (1, 0), (-1, 0)) visited = set([tuple(entrance)]) ans = inf while q: cur, step = q.popleft() x, y = cur for dx, dy in d: nx, ny = x + dx, y + dy if not (0 <= nx < m and 0 <= ny < n) or (nx, ny) in visited or M[nx][ny] == "+": continue if (0 in (nx, ny) or nx == m - 1 or ny == n - 1): ans = min(ans, step + 1) else: visited.add((nx, ny)) q += ((nx, ny), step + 1), return (ans, -1)[ans == inf]
nearest-exit-from-entrance-in-maze
Clean BFS in Python 3
mousun224
0
4
nearest exit from entrance in maze
1,926
0.49
Medium
27,163
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2842616/Python-Solution-Using-BFS-oror-Beats-100
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m,n = len(maze), len(maze[0]) que = collections.deque() que.append([entrance[0],entrance[1],0]) maze[entrance[0]][entrance[1]] = '+' while len(que)>0: x,y,cost = que.popleft() if [x,y] != entrance and (x==0 or y==0 or x==m-1 or y==n-1): return cost else: if x>0 and maze[x-1][y] == '.': maze[x-1][y] = '+' que.append([x-1,y,cost+1]) if x<m-1 and maze[x+1][y] == '.': maze[x+1][y] = '+' que.append([x+1,y,cost+1]) if y>0 and maze[x][y-1] == '.': maze[x][y-1] = '+' que.append([x,y-1,cost+1]) if y<n-1 and maze[x][y+1] == '.': maze[x][y+1] = '+' que.append([x,y+1,cost+1]) return -1
nearest-exit-from-entrance-in-maze
Python Solution, Using BFS || Beats 100%
aryan_codes_here
0
2
nearest exit from entrance in maze
1,926
0.49
Medium
27,164
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2839938/BFS-Modular-Solution-with-Input-Validation-The-Best
class Solution: def __init__(self): self.maze = None self.entrance = None self.rows, self.cols = 0, 0 def nearestExit(self, maze: list[list[str]], entrance: list[int]): self.configure(maze, entrance) self.is_empty(*entrance, 0) moves, index = deque([entrance]), 0 while moves: row, col = moves.popleft() # print(row, col) if self.is_exit(row, col): return self.maze[row][col] index += 1 moves += self.get_moves_and_mark(row, col) return -1 def configure(self, maze, entrance): self.maze = maze self.entrance = entrance self.rows = len(maze) assert self.rows > 0 self.cols = len(maze[0]) assert all(len(row_length) == self.cols for row_length in maze) assert all(all(cell in '.+' for cell in row) for row in maze) assert len(entrance) == 2 assert self.is_empty(*entrance) def is_empty(self, row, col, mark=None): empty = 0 <= row < self.rows and 0 <= col < self.cols and self.maze[row][col] == '.' if empty and mark is not None: self.maze[row][col] = mark return empty def is_exit(self, row, col): return (row in {0, self.rows-1} or col in {0, self.cols-1}) and [row, col] != self.entrance def get_moves_and_mark(self, row, col): return [[row + dy, col + dx] for (dy, dx) in ((-1, 0), (1, 0), (0, -1), (0, 1)) if self.is_empty(row + dy, col + dx, self.maze[row][col] + 1)]
nearest-exit-from-entrance-in-maze
BFS, Modular Solution with Input Validation, The Best
Triquetra
0
5
nearest exit from entrance in maze
1,926
0.49
Medium
27,165
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2837724/Python-Solution
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m = len(maze) n = len(maze[0]) queue = deque() seen = set() moves = [[0, 1], [0, -1], [1, 0], [-1, 0]] steps = 0 queue.append(entrance) while queue: count = len(queue) steps += 1 for _ in range(count): cell = queue.popleft() for move in moves: x = cell[0] + move[0] y = cell[1] + move[1] if x < 0 or x >= m: continue if y < 0 or y >= n: continue if maze[x][y] == '+': continue if x == entrance[0] and y == entrance[1]: continue if x == 0 or x == m - 1: return steps if y == 0 or y == n - 1: return steps if (x, y) in seen: continue queue.append((x, y)) seen.add((x, y)) return -1
nearest-exit-from-entrance-in-maze
Python Solution
mansoorafzal
0
12
nearest exit from entrance in maze
1,926
0.49
Medium
27,166
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2837334/simple-and-efficient
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: paths = collections.deque([entrance]) maze[entrance[0]][entrance[1]] = "+" steps = 0 while paths: for _ in range(len(paths)): row, col = paths.pop() if steps > 0 and (row in (0, len(maze)-1) or col in (0, len(maze[0])-1)): return steps if row > 0 and maze[row-1][col] == ".": paths.appendleft((row-1, col)) maze[row-1][col] = "+" if row < len(maze)-1 and maze[row+1][col] == ".": paths.appendleft((row+1, col)) maze[row+1][col] = "+" if col > 0 and maze[row][col-1] == ".": paths.appendleft((row, col-1)) maze[row][col-1] = "+" if col < len(maze[0])-1 and maze[row][col+1] == ".": paths.appendleft((row, col+1)) maze[row][col+1] = "+" steps += 1 return -1
nearest-exit-from-entrance-in-maze
simple and efficient
TrickyUnicorn
0
5
nearest exit from entrance in maze
1,926
0.49
Medium
27,167
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836955/BFS-and-Python
class Solution: def isItExit(self, curr_x, curr_y, n,m): return curr_x == 0 or curr_y == 0 or curr_x == n-1 or curr_y == m-1 def isPossibleToProcess(self, new_x, new_y, maze, n,m): return 0<= new_x < n and 0<= new_y < m and maze[new_x][new_y] == "." def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: dirxn = ((-1,0), (1,0), (0, -1), (0,1)) n,m = len(maze), len(maze[0]) x, y = entrance maze[x][y] = "+" queue = collections.deque() queue.append((x,y,0)) result = -1 while queue: curr_x, curr_y, curr_result = queue.popleft() for dx, dy in dirxn: new_x = curr_x + dx new_y = curr_y + dy if(self.isPossibleToProcess(new_x, new_y, maze, n,m)): if(self.isItExit(new_x, new_y, n,m)): return curr_result + 1 # we will block the current tiles maze[new_x][new_y] = "+" queue.append((new_x, new_y, curr_result+1)) return result
nearest-exit-from-entrance-in-maze
BFS and Python
Sanjaychandak95
0
6
nearest exit from entrance in maze
1,926
0.49
Medium
27,168
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836652/BFS-solution-python3-with-explanation
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: ROWS, COLS = len(maze), len(maze[0]) #for finding all the available exits exits = set() for r in range(ROWS): for c in range(COLS): if (maze[r][c] == '.' and ((r == 0 or r == ROWS - 1) or (c == 0 or c == COLS - 1))): exits.add((r, c)) #removing the entrance, if it is in exits if tuple(entrance) in exits: exits.remove(tuple(entrance)) directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] #normal BFS q = deque() q.append([entrance[0], entrance[1], 0]) while q: r, c, steps = q.popleft() if (r, c) in exits: return steps for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < ROWS and 0 <= nc < COLS and maze[nr][nc] == '.': #changing the state of the visited place in the maze maze[nr][nc] = 0 q.append([nr, nc, steps + 1]) return -1
nearest-exit-from-entrance-in-maze
BFS solution python3 with explanation
mohitkumar36
0
3
nearest exit from entrance in maze
1,926
0.49
Medium
27,169
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836556/1926.-Nearest-Exit-from-Entrance-in-Maze-or-Python3
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows, cols = len(maze), len(maze[0]) #create list of directions we can travel in dirs = ((1, 0), (-1, 0), (0, 1), (0,-1)) #create values for the entrance and mark it as visited sr, sc = entrance maze[sr][sc] = "+" #create a queue and add the entrance queue = collections.deque() queue.append([sr, sc, 0]) while queue: #set current row, current column, current distance to the next cell in the queue cr, cc, cd = queue.popleft() #check every direction for d in dirs: #next row/column equals the current row/column plus the direction nr = cr + d[0] nc = cc + d[1] #check to see if the next cell is in the maze and open if (0 <= nr < rows) and (0 <= nc < cols) and maze[nr][nc] == ".": #check to see if its on the edge meaning an exit if 0 == nr or nr == rows-1 or 0 == nc or nc == cols-1: #return the current distance + 1 return cd + 1 #if not an exit then mark it as visited and add it to queue maze[nr][nc] = "+" queue.append([nr, nc, cd+1]) #return -1 if nothing is found return -1
nearest-exit-from-entrance-in-maze
1926. Nearest Exit from Entrance in Maze | Python3
AndrewMitchell25
0
6
nearest exit from entrance in maze
1,926
0.49
Medium
27,170
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836261/Python-Solution-or-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: EMPTY, WALL = '.', '+' directions = {(0, 1), (0, -1), (1, 0), (-1, 0)} m, n = len(maze), len(maze[0]) q, visited = deque(), set() def in_bounds(r, c): return 0 <= r < m and 0 <= c < n def is_exit(r, c): return maze[r][c] == EMPTY and (r == 0 or r == m-1 or c == 0 or c == n-1) def is_wall(r, c): return maze[r][c] == WALL ans = 0 q.append((entrance[0], entrance[1])) visited.add((entrance[0], entrance[1])) while q: ans += 1 for i in range(len(q)): r, c = q.popleft() for Δr, Δc in directions: rr, cc = r + Δr, c + Δc if not in_bounds(rr, cc) or (rr, cc) in visited or is_wall(rr, cc): continue if is_exit(rr, cc): return ans q.append((rr, cc)) visited.add((rr, cc)) return -1
nearest-exit-from-entrance-in-maze
Python Solution | BFS
on_danse_encore_on_rit_encore
0
7
nearest exit from entrance in maze
1,926
0.49
Medium
27,171
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836224/Python3-or-BFS-%2B-Heap-or-Shortest-path-or-Dijkstra
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: dirList = [[0, 1], [0, -1], [1, 0], [-1, 0]] bfs = [(0, entrance[0], entrance[1])] seen = {} n, m = len(maze), len(maze[0]) def isExit(x, y): if x == entrance[0] and y == entrance[1]: return False return x == 0 or y == 0 or x == n-1 or y == m-1 while bfs: curd, curx, cury = heapq.heappop(bfs) if maze[curx][cury] == '+': continue maze[curx][cury] = '+' if isExit(curx, cury): return curd for dx, dy in dirList: x, y = curx + dx, cury + dy if x < 0 or x >= n or y < 0 or y >= m: continue heapq.heappush(bfs, (curd+1, x, y)) return -1
nearest-exit-from-entrance-in-maze
Python3 | BFS + Heap | Shortest path | Dijkstra
vikinam97
0
4
nearest exit from entrance in maze
1,926
0.49
Medium
27,172
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836211/Clean-BFS-Solution-oror-Python-3-oror-Easy-Approach
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m,n=len(maze),len(maze[0]) exit=set() for i in range(m): if maze[i][0]=="." and [i,0]!=entrance: exit.add((i,0)) if maze[i][n-1]=="." and [i,n-1]!=entrance: exit.add((i,n-1)) for i in range(n): if maze[0][i]=="." and [0,i]!=entrance: exit.add((0,i)) if maze[m-1][i]=="." and [m-1,i]!=entrance: exit.add((m-1,i)) def bfs(maze,i,j): nonlocal exit,m,n seen=set() seen.add((i,j)) q=[(i,j)] ans=0 while q: for i in range(len(q)): x,y=q.pop(0) if (x,y) in exit: return ans for cx,cy in [(1,0),(0,1),(-1,0),(0,-1)]: nx,ny=x+cx,y+cy if 0<=nx<m and 0<=ny<n and maze[nx][ny]=="." and (nx,ny) not in seen: q.append((nx,ny)) seen.add((nx,ny)) ans+=1 return -1 return bfs(maze,entrance[0],entrance[1])
nearest-exit-from-entrance-in-maze
Clean BFS Solution || Python 3 || Easy Approach
aditya1292
0
7
nearest exit from entrance in maze
1,926
0.49
Medium
27,173
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836158/Python3-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m = len(maze) n = len(maze[0]) startX, startY = entrance DQ = deque([[startX, startY, 0]]) visited = {(startX, startY)} while DQ: X, Y, dist = DQ.popleft() for x, y in [(0, 1), (1, 0), (0, -1), (-1, 0)]: currX, currY = X + x, Y + y if 0 <= currX < m and 0 <= currY < n and (currX, currY) not in visited and maze[currX][currY] == '.': if currX == 0 or currX == m - 1 or currY == 0 or currY == n - 1: return dist + 1 DQ.append([currX, currY, dist + 1]) visited.add((currX, currY)) return -1
nearest-exit-from-entrance-in-maze
Python3 BFS
mediocre-coder
0
4
nearest exit from entrance in maze
1,926
0.49
Medium
27,174
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2836152/Python3-using-BFS-with-List-%2B-Set
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: vis = set([tuple(entrance)]) bfs = [[*entrance, 0]] for r, c, steps in bfs: for nr, nc in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]: if not 0 <= nr < len(maze) or not 0 <= nc < len(maze[0]): continue if maze[nr][nc] == '+': continue if (nr, nc) in vis: continue if nr == 0 or nc == 0 or nr+1 == len(maze) or nc+1 == len(maze[0]): return steps + 1 vis.add((nr, nc)) bfs.append([nr, nc, steps+1]) return -1
nearest-exit-from-entrance-in-maze
Python3 using BFS with List + Set
Nesop
0
8
nearest exit from entrance in maze
1,926
0.49
Medium
27,175
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835963/Python3-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m, n = len(maze), len(maze[0]) entrance = tuple(entrance) lv = 1 seen = {entrance} curLv = [entrance] while curLv: nxtLv = [] for r,c in curLv: for nr,nc in [(r+1,c),(r-1,c),(r,c+1),(r,c-1)]: if 0<=nr<m and 0<=nc<n and maze[nr][nc]=="." \ and (nr,nc) not in seen: if nr in (0,m-1) or nc in (0,n-1): return lv nxtLv.append((nr,nc)) seen.add((nr,nc)) curLv = nxtLv lv += 1 return -1
nearest-exit-from-entrance-in-maze
[Python3] BFS
ruosengao
0
6
nearest exit from entrance in maze
1,926
0.49
Medium
27,176
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835737/Python3-BFS-simple-way
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: # BFS q = [[entrance[0],entrance[1]]] step = 0 rows = len(maze) cols = len(maze[0]) # clockwise directions = [[0,1],[1,0],[0,-1],[-1,0]] maze[entrance[0]][entrance[1]] = '+' while q: for _ in range(len(q)): r,c = q.pop(0) # q.append so can not check this is '+' # entrance can not be exit if (0 == r or 0 == c or r == rows-1 or c ==cols-1) and [r,c] != [entrance[0], entrance[1]]: return step for x, y in directions: new_x, new_y = r+x, c+y if 0 <= new_x < rows and 0 <= new_y < cols and maze[new_x][new_y]=='.': # Cuz change '.' to '+' maze[new_x][new_y] = '+' q.append([new_x,new_y]) step += 1 return -1
nearest-exit-from-entrance-in-maze
Python3 BFS simple way
dad88htc816
0
7
nearest exit from entrance in maze
1,926
0.49
Medium
27,177
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835734/Python-or-Java-or-Easy-BFS-Solution
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: queue = [] directions = [[0, -1], [0, 1], [1, 0], [-1, 0]] rows = len(maze) columns = len(maze[0]) ans = 0 # offer and mark visited queue.append(entrance) maze[entrance[0]][entrance[1]] = '+' while queue: size = len(queue) ans += 1 while size > 0: size -= 1 position = queue.pop(0) x = position[0] y = position[1] for dir in directions: newX = x + dir[0] newY = y + dir[1] if newX < 0 or newY < 0 or newX > rows - 1 or newY > columns - 1 or maze[newX][newY] == '+': continue elif newX == 0 or newY == 0 or newX == rows - 1 or newY == columns - 1: return ans # offer and mark visited queue.append([newX, newY]) maze[newX][newY] = '+' return -1
nearest-exit-from-entrance-in-maze
Python | Java | Easy BFS Solution
rahul_mishra_
0
8
nearest exit from entrance in maze
1,926
0.49
Medium
27,178
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835603/Python-or-BFS-solution-using-queue
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows, cols = len(maze), len(maze[0]) q = deque([entrance]) visited = set() visited.add((entrance[0], entrance[1])) directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] steps = 0 while q: for i in range(len(q)): r, c = q.popleft() if [r, c] != entrance and (r == 0 or r == rows - 1 or c == 0 or c == cols - 1): return steps for dr, dc in directions: nr, nc = r + dr, c + dc if nr in range(rows) and nc in range(cols) and (nr, nc) not in visited and maze[nr][nc] == '.': visited.add((nr, nc)) q.append([nr, nc]) steps += 1 return -1
nearest-exit-from-entrance-in-maze
Python | BFS solution using queue
KevinJM17
0
4
nearest exit from entrance in maze
1,926
0.49
Medium
27,179
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835566/Python-soln-using-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: n=len(maze) m=len(maze[0]) q=deque() q.append([entrance[0],entrance[1],0]) ret=[] visit=set() while q: [x,y,s]=q.popleft() if not (0<=x<n and 0<=y<m): continue if (x,y) in visit or maze[x][y]=='+': continue if x==n-1 or x==0 or y==m-1 or y==0: if s: return s visit.add((x,y)) q.append([x+1,y,s+1]) q.append([x-1,y,s+1]) q.append([x,y+1,s+1]) q.append([x,y-1,s+1]) return -1
nearest-exit-from-entrance-in-maze
Python soln using BFS
DhruvBagrecha
0
4
nearest exit from entrance in maze
1,926
0.49
Medium
27,180
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835526/Python-or-BFS-solution
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: q = deque([entrance]) m, n = len(maze) - 1, len(maze[0]) - 1 used, ans, dist = {tuple(entrance)}, 1e18, defaultdict(int) dist[tuple(entrance)] = 0 while q: nx = q.popleft() if (nx[0] == m or nx[1] == n or nx[0] == 0 or nx[1] == 0) and nx != entrance: ans = min(ans, dist[tuple(nx)]) for f, s in [[1, 0], [-1, 0], [0, 1], [0, -1]]: x, y = f + nx[0], s + nx[1] if 0 <= x <= m and 0 <= y <= n and (x, y) not in used and maze[x][y] == '.': dist[(x, y)] = dist[tuple(nx)] + 1 q.append((x, y)) used.add((x, y)) return -1 if ans == 1e18 else ans
nearest-exit-from-entrance-in-maze
Python | BFS solution
LordVader1
0
8
nearest exit from entrance in maze
1,926
0.49
Medium
27,181
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835421/BFS-Easy-Solution-in-O(N)
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows = len(maze) columns = len(maze[0]) q = deque([(entrance[0], entrance[1], 0)]) visited = set() while q: i, j, steps = q.popleft() if (i == rows - 1 or i == 0 or j == columns - 1 or j == 0) and steps != 0: return steps visited.add((i, j)) for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]: ni, nj = (di + i), (dj + j) if 0 <= ni < rows and 0 <= nj < columns and (ni, nj) not in visited and maze[ni][nj] == '.': visited.add((ni, nj)) q.append((ni, nj, steps + 1)) return -1
nearest-exit-from-entrance-in-maze
BFS - Easy Solution in O(N)
user6770yv
0
5
nearest exit from entrance in maze
1,926
0.49
Medium
27,182
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835283/Python-Simple-BFS-(TLE-explanation)
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: count = 1 queue = [[entrance[0], entrance[1]]] row = len(maze) col = len(maze[0]) maze[entrance[0]][entrance[1]] = '+' while(queue): for _ in range(len(queue)): cur = queue.pop(0) #if mark "+" in there we will got the TLE because we will count duplicate #ex:queue[[1,2], [2,1]] if [1,1] is '.', then we will add [1,1] to queue two times #maze[cur[0]][cur[1]] = '+' for dx, dy in [[1, 0], [-1, 0], [0, 1], [0, -1]]: if(0 <= cur[0] + dx < row and 0 <= cur[1] + dy < col and maze[cur[0] + dx][cur[1] + dy] == '.'): #mark "+" in there so we don't count duplicate maze[cur[0] + dx][cur[1] + dy] = '+' if(cur[0] + dx == 0 or cur[0] + dx == row - 1 or cur[1] + dy == 0 or cur[1] + dy == col - 1): return count queue.append([cur[0] + dx, cur[1] + dy]) count += 1 return -1
nearest-exit-from-entrance-in-maze
Python Simple BFS (TLE explanation)
55337123kk3
0
5
nearest exit from entrance in maze
1,926
0.49
Medium
27,183
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835093/Python-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: Q = [entrance] Q_next = [] maze[entrance[0]][entrance[1]] = '+' near = [[1, 0], [-1, 0], [0, 1], [0, -1]] row, col = len(maze) - 1, len(maze[0]) - 1 step = 0 while len(Q) > 0: curr = Q.pop(0) for n in near: next = [curr[0] + n[0], curr[1] + n[1]] if (next[0] >= 0) and (next[1] >= 0) and (next[0] <= row) and (next[1] <= col): if maze[next[0]][next[1]] == '.': if (next[0] == 0) or (next[1] == 0) or (next[0] == row) or (next[1] == col): return step + 1 Q_next.append(next) maze[next[0]][next[1]] = '+' if len(Q) == 0: Q, Q_next = Q_next, Q step += 1 return -1
nearest-exit-from-entrance-in-maze
[Python] BFS
mingyang-tu
0
10
nearest exit from entrance in maze
1,926
0.49
Medium
27,184
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2835041/Easy-for-understand
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows = len(maze) cols = len(maze[0]) queue = collections.deque() queue.append((entrance[0], entrance[1], 0)) seen = set() mn = -1 while queue: row, col, step = queue.popleft() if mn != - 1 and mn < step: continue if row >= rows or row < 0 or col >= cols or col < 0: continue if maze[row][col] == '+' or (row, col) in seen: continue seen.add((row, col)) if not (row == entrance[0] and col == entrance[1]) and (row in [0, rows - 1] or col in [0, cols - 1]): return step queue.append((row - 1, col, step + 1)) queue.append((row + 1, col, step + 1)) queue.append((row, col - 1, step + 1)) queue.append((row, col + 1, step + 1)) return -1
nearest-exit-from-entrance-in-maze
Easy for understand
lllymka
0
16
nearest exit from entrance in maze
1,926
0.49
Medium
27,185
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834999/Python-oror-Easy-Solution-oror-O(N)-oror-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: n, m = len(maze), len(maze[0]) visit = [] for i in range(n): visit.append([False]*m) def isValid(i, j): return i >= 0 and j >= 0 and i < n and j < m and not visit[i][j] and maze[i][j] == "." def isExit(i, j): return (i == 0 or i == n - 1 or j == 0 or j == m - 1) and not (entrance[0] == i and entrance[1] == j) ans = [float('inf')] def get_ans(i, j, step): queue = [[i, j, step]] while len(queue) != 0: r_queue = [] while len(queue) != 0: i, j, step = queue.pop() if isExit(i, j): ans[0] = min(ans[0], step) d = [[1, 0], [-1, 0], [0, 1], [0, -1]] for dx, dy in d: n_i, n_j = i + dx, j + dy if isValid(n_i, n_j): visit[n_i][n_j] = True r_queue.append([n_i, n_j, step + 1]) queue = r_queue get_ans(entrance[0], entrance[1], 0) return ans[0] if ans[0] != float('inf') else -1
nearest-exit-from-entrance-in-maze
Python || Easy Solution || O(N) || BFS
Rahul_Kantwa
0
8
nearest exit from entrance in maze
1,926
0.49
Medium
27,186
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834946/Typical-BFS-in-Python3
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m, n = len(maze), len(maze[0]) exits = set() # add all the exits from the matrix for i in range(m): for j in range(n): if ((i == 0 or i == m - 1) or (j == 0 or j == n - 1)) and [i, j] != entrance and maze[i][j] == ".": exits.add((i, j)) if not exits: return -1 q = [] visited = set() q.append(entrance + [0]) while q: i, j, distance = q.pop(0) if (i, j) in exits: return distance for di, dj in ((0, 1), (0, -1), (1, 0), (-1, 0)): ni, nj = i + di, j + dj if 0 <= ni < m and 0 <= nj < n and maze[ni][nj] != "+" and (ni, nj) not in visited: q.append([ni, nj, distance + 1]) visited.add((ni, nj)) return -1
nearest-exit-from-entrance-in-maze
Typical BFS in Python3
hahashabi
0
9
nearest exit from entrance in maze
1,926
0.49
Medium
27,187
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834811/python3-Shortest-path-Dijkstra-sol-for-reference
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: R = len(maze) C = len(maze[0]) dp = [[float('inf') for _ in range(C)] for _ in range(R)] st = [(0, tuple(entrance))] visited = defaultdict(bool) visited[tuple(entrance)] = True while st: dist, point = heapq.heappop(st) x,y = point for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]: nx = x + dx ny = y + dy if nx >= 0 and ny >= 0 and nx < R and ny < C and maze[nx][ny] == "." and not visited[(nx,ny)]: visited[(nx,ny)] = True dp[nx][ny] = min(dp[nx][ny], dist + 1) heapq.heappush(st, (dp[nx][ny], (nx, ny))) ans = min(min(dp[0]), min(dp[-1]), min([dp[i][0] for i in range(R)]), min([dp[i][-1] for i in range(R)])) return ans if ans != float('inf') else -1
nearest-exit-from-entrance-in-maze
[python3] Shortest path Dijkstra sol for reference
vadhri_venkat
0
6
nearest exit from entrance in maze
1,926
0.49
Medium
27,188
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834805/Simple-bfs-using-Python3.-Very-easy-to-understand.
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: def helper(r,c): queue = collections.deque() queue.append((r,c,0)) visited = set([(r,c)]) while queue: r, c, dist = queue.popleft() if ([r, c] != entrance) and (r == 0 or r == len(maze)-1 or c == 0 or c == len(maze[0]) - 1): #found exit on the edge return dist else: for r1, c1 in [(r, c+1), (r, c-1), (r-1, c), (r+1, c)]: #for all valid neighbors that are in bounds and don't have a wall, add them to the queue if r1 < len(maze) and r1 >= 0 and c1 < len(maze[0]) and c1 >= 0 and (r1, c1) not in visited and maze[r1][c1] == '.': queue.append((r1,c1,dist+1)) visited.add((r1,c1)) return -1 d = helper(entrance[0],entrance[1]) return d
nearest-exit-from-entrance-in-maze
Simple bfs using Python3. Very easy to understand.
dkashi
0
7
nearest exit from entrance in maze
1,926
0.49
Medium
27,189
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834770/Python3-Solution-with-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows=len(maze) cols=len(maze[0]) sx,sy=entrance maze[sx][sy]="s" for x in range(rows): if maze[x][0]==".": maze[x][0]="e" if maze[x][-1]==".": maze[x][-1]="e" for y in range(cols): if maze[0][y]==".": maze[0][y]="e" if maze[-1][y]==".": maze[-1][y]="e" directions=[(0,1),(1,0),(0,-1),(-1,0)] done=[[False]*cols for _ in range(rows)] queue=collections.deque() queue.append((0,sx,sy)) done[sx][sy]=True while len(queue)>0: d,x,y=queue.popleft() for dx,dy in directions: nx,ny=x+dx,y+dy if 0<=nx<rows and 0<=ny<cols and not done[nx][ny]: if maze[nx][ny]==".": done[nx][ny]=True queue.append((d+1,nx,ny)) elif maze[nx][ny]=="e": return d+1 return -1
nearest-exit-from-entrance-in-maze
Python3 Solution with BFS
Motaharozzaman1996
0
6
nearest exit from entrance in maze
1,926
0.49
Medium
27,190
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834761/BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: m, n = len(maze), len(maze[0]) visited = set() # 记录去过的格子 def next_neighbor(x, y): # 邻居生成器 for xx, yy in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): if 0 <= xx < m and 0 <= yy < n: yield xx, yy maze[entrance[0]][entrance[1]] = '+' # 把entrance标记成墙壁避免一开始就从entrance溜出去 queue = [tuple(entrance)] # 当前边界就是entrance一格 visited.add(tuple(entrance)) count = 0 while queue: # 只要还有边界可探就继续 temp_queue = [] # 记录新边界 for x, y in queue: if (x == 0 or x == m - 1 or y == 0 or y == n - 1) and maze[x][y] == '.': # 判断出口 return count for xx, yy in next_neighbor(x, y): # 遍历边界格子的所有邻居 if maze[xx][yy] == '.' and (xx, yy) not in visited: # 可以走而且没走过的格子就是新边界 temp_queue.append((xx, yy)) visited.add((xx, yy)) queue = temp_queue # 更新边界 count += 1 # 记录回合数 return -1 # 走投无路GG
nearest-exit-from-entrance-in-maze
BFS 广度优先搜索习题
nathentasty
0
3
nearest exit from entrance in maze
1,926
0.49
Medium
27,191
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834664/Simple-Python-BFS
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: queue = [(entrance, 0),] maze[entrance[0]][entrance[1]] = '+' while(not len(queue) == 0): (current, length) = queue.pop(0) if(current[1]+1 < len(maze[0])): if(maze[current[0]][current[1]+1] == '.'): queue.append(([current[0],current[1]+1], length+1)) maze[current[0]][current[1]+1] = '+' else: if(length > 0): return length if(current[1]-1 >= 0): if(maze[current[0]][current[1]-1] == '.'): queue.append(([current[0],current[1]-1], length+1)) maze[current[0]][current[1]-1] = '+' else: if(length > 0): return length if(current[0]+1 < len(maze)): if(maze[current[0]+1][current[1]] == '.'): queue.append(([current[0]+1,current[1]], length+1)) maze[current[0]+1][current[1]] = '+' else: if(length > 0): return length if(current[0]-1 >= 0): if(maze[current[0]-1][current[1]] == '.'): queue.append(([current[0]-1,current[1]], length+1)) maze[current[0]-1][current[1]] = '+' else: if(length > 0): return length return -1
nearest-exit-from-entrance-in-maze
Simple Python BFS
denfedex
0
3
nearest exit from entrance in maze
1,926
0.49
Medium
27,192
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834652/Python-BFS-approach-O(n)-time-O(n)-memory
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: steps = 0 n = len(maze) m = len(maze[0]) i0, j0 = entrance[0], entrance[1] maze[i0][j0] = '+' level = [[i0, j0]] neighbors = [[1, 0], [-1, 0], [0, 1], [0, -1]] while level: next_level = [] steps += 1 for i, j in level: for di, dj in neighbors: i1, j1 = i + di, j + dj if 0 <= i1 < n and 0 <= j1 < m: if maze[i1][j1] == '.': if i1 == 0 or i1 == n-1 or j1 ==0 or j1 == m-1: return steps maze[i1][j1] = '+' next_level.append([i1, j1]) level = next_level return -1
nearest-exit-from-entrance-in-maze
[Python] BFS approach O(n) time, O(n) memory
wtain
0
5
nearest exit from entrance in maze
1,926
0.49
Medium
27,193
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834623/Python3-BFS-%2B-Visted-Set-With-Helper-Function
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: visited, visit = set([(entrance[0], entrance[1])]), [(0,entrance[0], entrance[1])] def if_good_add(c, i, j): if (i,j) in visited or i<0 or j<0 or i>=len(maze) or j>=len(maze[0]) or maze[i][j] == '+': return False visit.append((c, i, j)) visited.add((i,j)) if i == 0 or i == len(maze) - 1 or j == 0 or j == len(maze[0]) - 1: return True while visit: c, i, j = visit.pop(0) for [id, jd] in [[1,0], [-1,0], [0,1], [0,-1]]: if if_good_add(c+1, i + id, j + jd): return c+1 return -1
nearest-exit-from-entrance-in-maze
Python3 BFS + Visted Set With Helper Function
godshiva
0
1
nearest exit from entrance in maze
1,926
0.49
Medium
27,194
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2834598/Python-or-BFS-search
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows, cols = len(maze), len(maze[0]) bfsQue = [[entrance, 0]] maze[entrance[0]][entrance[1]] = '+' movements = [[-1, 0], [1, 0], [0, -1], [0, 1]] while(bfsQue): top, step = bfsQue[0] s1 = step + 1 for m in movements: nr, nc = top[0] + m[0], top[1] + m[1] if(nr < 0 or nc < 0 or nr >= rows or nc >= cols or maze[nr][nc] != '.'): continue if(nr == rows - 1 or nr == 0 or nc == cols - 1 or nc == 0): return s1 maze[nr][nc] = '+' bfsQue.append([[nr, nc], s1]) bfsQue.pop(0) return -1
nearest-exit-from-entrance-in-maze
Python | BFS search
CosmosYu
0
2
nearest exit from entrance in maze
1,926
0.49
Medium
27,195
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2614850/Python-Readable-BFS-(and-explanation-why-not-DFS)
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: # make bfs as we want to search shortest path queue = collections.deque() queue.append((entrance[0], entrance[1], 0)) # get the matrix sizes m = len(maze) - 1 n = len(maze[0]) - 1 # check for empty queue while queue: # pop the position rx, cx, steps = queue.popleft() # check if we hit a wall (or we already visited) if maze[rx][cx] == '+': continue # tell that we visited (build a wall!) # as we do bfs we can be shure we are on the # shortest path maze[rx][cx] = "+" # check if it is exit if rx == 0 or rx == m or cx == 0 or cx == n: # check that it is something else than entrace if not (rx == entrance[0] and cx == entrance[1]): # return our shortest path return steps # go further in all directions (and check that we stay in bounds) if rx < m: queue.append((rx+1, cx, steps+1)) if rx > 0: queue.append((rx-1, cx, steps+1)) if cx < n: queue.append((rx, cx+1, steps+1)) if cx > 0: queue.append((rx, cx-1, steps+1)) # return the minimum return -1
nearest-exit-from-entrance-in-maze
[Python] - Readable BFS (and explanation why not DFS)
Lucew
0
19
nearest exit from entrance in maze
1,926
0.49
Medium
27,196
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/2034044/Python-simple-and-efficient-BFS-solution
class Solution: def nearestExit(self, grid: List[List[str]], entrance: List[int]) -> int: q = deque() q.append((entrance[0], entrance[1], 0)) seen = set() while q : i, j, d = q.popleft() if (i == 0 or j == 0 or i == len(grid) - 1 or j == len(grid[0]) - 1) and [i, j] != entrance : return d for x, y in ((i-1, j), (i, j-1), (i+1, j), (i, j+1)) : if 0 <= x < len(grid) and 0 <= y < len(grid[0]) : if (x, y) not in seen and grid[x][y] == "." : seen.add((x, y)) q.append((x, y, d+1)) # print(q) return -1
nearest-exit-from-entrance-in-maze
Python simple and efficient BFS solution
runtime-terror
0
35
nearest exit from entrance in maze
1,926
0.49
Medium
27,197
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1888635/Python-BFS-solution
class Solution: def nearestExit(self, A: List[List[str]], st: List[int]) -> int: bounds = {(st[0], st[1])} # We will store our latest checked cells here A[st[0]][st[1]] = '1' # We are going to change values of checked cells m, n = len(A), len(A[0]) step = 1 while bounds: new = [] for i,j in bounds: for d in [(1,0),(-1,0),(0,1),(0,-1)]: # Check all the adjacent cells x,y = i+d[0], j+d[1] if 0 <= x < m and 0 <= y < n: # If the current cell is inside the borders if A[x][y] == '.': # ... and if it is not the wall if x in [0, m-1] or y in [0, n-1]: # check if it's an exit return step A[x][y] = '1' # ...if no, add it to list of our latest checked cells new.append((x,y)) step += 1 bounds = new return -1
nearest-exit-from-entrance-in-maze
Python BFS solution
markkorvin
0
48
nearest exit from entrance in maze
1,926
0.49
Medium
27,198
https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1823249/Python-or-BFS-Solution
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: rows = len(maze) cols = len(maze[0]) sr, sc = entrance #starting row, starting column visited = {(sr,sc)} q = deque([(sr,sc,0)]) # 0 = initial distance while q: x, y, d = q.popleft() # d = distance for dx, dy in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]: if 0 <= dx < rows and 0 <= dy < cols and (dx,dy) not in visited and maze[dx][dy] == ".": visited.add((dx,dy)) q.append((dx,dy,d+1)) if dx == 0 or dx == rows - 1 or dy == 0 or dy == cols - 1: # check if reached the border return d + 1 return -1
nearest-exit-from-entrance-in-maze
Python | BFS Solution
jgroszew
0
42
nearest exit from entrance in maze
1,926
0.49
Medium
27,199