锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
2 #Runtime: 44 ms (Beats 7.3%)
3 #Memory: 16.2 MB (Beats 35.94%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def tree2str(self, root):
13 """
14 :type root: TreeNode
15 :rtype: str
16 """
17 self.ans = ""
18 def DFS(node):
19 self.ans += str(node.val)
20 if node.left or node.right:
21 self.ans += '('
22 if node.left:
23 DFS(node.left)
24 self.ans += ')'
25 if node.right:
26 self.ans += '('
27 DFS(node.right)
28 self.ans += ')'
29
30 if root:
31 DFS(root)
32 return self.ans
]]>
2 #Runtime: 26 ms (Beats 68.6%)
3 #Memory: 17.7 MB (Beats 71.73%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def largestValues(self, root):
13 """
14 :type root: TreeNode
15 :rtype: List[int]
16 """
17 if not root:
18 return []
19 q = deque([root])
20 ans = []
21 while q:
22 sz = len(q)
23 t = float('-inf')
24 while sz:
25 sz -= 1
26 node = q.popleft()
27 t = max(t, node.val)
28 if node.left:
29 q.append(node.left)
30 if node.right:
31 q.append(node.right)
32 ans.append(t)
33 return ans
]]>
2 #Runtime: 224 ms (Beats 92.11%)
3 #Memory: 15.5 MB (Beats 71.5%錛?/span>
4
5 class Solution(object):
6 def validateBinaryTreeNodes(self, n, leftChild, rightChild):
7 """
8 :type n: int
9 :type leftChild: List[int]
10 :type rightChild: List[int]
11 :rtype: bool
12 """
13 rt = 0
14 child_nodes = set(leftChild + rightChild)
15 for i in xrange(n):
16 if i not in child_nodes:
17 rt = i
18 vis = set()
19 q = deque([rt])
20 while q:
21 node = q.popleft()
22 if node in vis:
23 return False
24 vis.add(node)
25 if leftChild[node] != -1:
26 q.append(leftChild[node])
27 if rightChild[node] != -1:
28 q.append(rightChild[node])
29 return len(vis) == n
]]>
2 #Runtime: 76 ms (Beats 100%)
3 #Memory: 14.2 MB (Beats 87.50%)
4
5 class Solution(object):
6 def shortestPathLength(self, graph):
7 """
8 :type graph: List[List[int]]
9 :rtype: int
10 """
11 n = len(graph)
12 vis_mask = (1 << n) - 1
13 q = deque()
14 vis = [[0] * n for _ in range(vis_mask + 1)]
15 for x in xrange(n):
16 ini_mask = 1 << x
17 q.append((x, ini_mask, 1))
18 vis[ini_mask][x] = 1
19 while q:
20 t = q.popleft()
21 cur_node, cur_mask, cur_len = t
22 if cur_mask == vis_mask:
23 return cur_len - 1
24 for nei in graph[cur_node]:
25 new_mask = cur_mask | (1 << nei)
26 if vis[new_mask][nei]:
27 continue
28 q.append((nei, new_mask, cur_len + 1))
29 vis[new_mask][nei] = 1
30 return -1
]]>
2 #Runtime: 62 ms (Beats 38.57%)
3 #Memory: 14.1 MB (Beats 53.57%)
4
5 class Solution(object):
6 def findItinerary(self, tickets):
7 """
8 :type tickets: List[List[str]]
9 :rtype: List[str]
10 """
11 node = defaultdict(list)
12 for (x, y) in tickets:
13 node[x] += y,
14 self.ans = ["JFK"]
15 def DFS(st):
16 if len(self.ans) == len(tickets) + 1:
17 return self.ans
18 tp_dst = sorted(node[st])
19 for dst in tp_dst:
20 node[st].remove(dst)
21 self.ans += dst,
22 ok = DFS(dst)
23 if ok:
24 return ok
25 self.ans.pop()
26 node[st] += dst,
27 return DFS("JFK")
]]>
C++
2 //Runtime 48 ms (Beats 24.56%)
3
4 class Solution {
5 public:
6 vector<vector<int>> res;
7 int nt;
8
9 void DFS(int n, int k, vector<int> &tp, int pos) {
10 if(nt == k) {
11 res.push_back(tp);
12 return;
13 }
14 for(int i = pos; i <= n; ++i) {
15 tp.push_back(i);
16 nt++;
17 DFS(n, k, tp, i + 1);
18 tp.pop_back();
19 nt--;
20 }
21 }
22
23 vector<vector<int> > combine(int n, int k) {
24 vector<int> tp;
25 //sort(S.begin(), S.end());
26 res.clear();
27 nt = 0;
28 DFS(n, k, tp, 1);
29 return res;
30 }
31 };
Python
2 #Runtime: 340 ms (Beats 77%)
3 #Memory: 14.9 MB (Beats 55.68%)
4
5 class Solution(object):
6 def combine(self, n, k):
7 """
8 :type n: int
9 :type k: int
10 :rtype: List[List[int]]
11 """
12 self.ans = []
13 def dfs(tp, p):
14 if len(tp) == k:
15 self.ans.append(tp[:])
16 return
17 for i in range(p, n + 1):
18 tp.append(i)
19 dfs(tp, i + 1)
20 tp.pop()
21 dfs([], 1)
22 return self.ans
]]>
2 #Runtime: 225 ms (Beats 75.30%)
3 #Memory: 26.5 MB (Beats 13.8%)
4
5 class Solution:
6 def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
7 d = [[1, 2], [2, 1], [1, -2], [2, -1], [-1, 2], [-2, 1], [-1, -2], [-2, -1]]
8
9 @lru_cache(None)
10 def dfs(x, y, k):
11 if k == 0:
12 return 1
13 ans = 0
14 for dx, dy in d:
15 tx = x + dx
16 ty = y + dy
17 if 0 <= tx < n and 0 <= ty < n:
18 ans += dfs(tx, ty, k - 1)
19 return ans
20 if not k:
21 return 1
22 return dfs(row, column, k) / 8**k
]]>
2 #Runtime: 999 ms (Beats 60%)
3 #Memory: 133.9 MB (Beats 20%)
4
5 class Solution(object):
6 def maxValue(self, events, k):
7 """
8 :type events: List[List[int]]
9 :type k: int
10 :rtype: int
11 """
12 n = len(events)
13 events.sort(key=lambda x: x[0])
14 dp = [[-1] * n for _ in range(k + 1)]
15
16 def DFS(idx, cnt):
17 if cnt == 0 or idx == len(events):
18 return 0
19 if dp[cnt][idx] != -1:
20 return dp[cnt][idx]
21 dp[cnt][idx] = max(DFS(idx + 1, cnt), events[idx][2] + DFS(bsearch(events[idx][1]), cnt - 1))
22 return dp[cnt][idx]
23
24 def bsearch(x):
25 l, r = 0, len(events) - 1
26 while l <= r:
27 mid = (l + r + 1) // 2
28 if events[mid][0] <= x:
29 l = mid + 1
30 else:
31 r = mid - 1
32 return l
33
34 return DFS(0, k)
]]>
BFS+鎷撴墤鎺掑簭鎬濇兂
2 #Runtime: 74 ms (Beats 75.97%)
3 #Memory: 14.5 MB (Beats 97.82%)
4
5 class Solution(object):
6 def canFinish(self, numCourses, prerequisites):
7 """
8 :type numCourses: int
9 :type prerequisites: List[List[int]]
10 :rtype: bool
11 """
12 ind = [0] * numCourses
13 adj = [[] for _ in range(numCourses)]
14 for i in range(len(prerequisites)):
15 a, b = prerequisites[i]
16 adj[b].append(a)
17 ind[a] += 1
18 q = deque()
19 for i in range(numCourses):
20 if not ind[i]:
21 q.append(i)
22 ans = []
23 while q:
24 node = q.popleft()
25 ans.append(node)
26 for i in adj[node]:
27 ind[i] -= 1
28 if ind[i] == 0:
29 q.append(i)
30 return len(ans) == numCourses
]]>
2 #Runtime: 25 ms (Beats 49.62%)
3 #Memory: 13.6 MB (Beats 74.5%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, x):
8 # self.val = x
9 # self.left = None
10 # self.right = None
11
12 class Solution(object):
13 def distanceK(self, root, target, k):
14 """
15 :type root: TreeNode
16 :type target: TreeNode
17 :type k: int
18 :rtype: List[int]
19 """
20 graph = {}
21 dep_target = 0
22 q = deque([[root, -1]])
23 while q:
24 node, f = q.popleft()
25 if node.val not in graph:
26 if f != -1:
27 graph[node.val] = [f]
28 graph[f].append(node.val)
29 else:
30 graph[node.val] = []
31 else:
32 graph[node.val].append(f)
33 graph[f].append(node.val)
34 if node.left:
35 q.append([node.left, node.val])
36 if node.right:
37 q.append([node.right, node.val])
38 q = deque([target.val])
39 dis = 0
40 ans = []
41 vis = set([target.val])
42 while q and dis < k:
43 sz = len(q)
44 while sz:
45 sz -= 1
46 node = q.popleft()
47 for i in graph[node]:
48 if i not in vis:
49 q.append(i)
50 vis.add(i)
51 dis += 1
52 if dis == k:
53 ans = list(q)
54 return ans
]]>
C++ BFS
2 //Runtime: 32 ms (Beats 100%)
3
4 /**
5 * Definition for binary tree
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 struct Que {
16 int depth;
17 TreeNode *p;
18 }q[100010];
19
20 int minDepth(TreeNode *root) {
21 int l = 0, r = 1, mx = 0, mi = 1000000;
22 if(root == NULL) return 0;
23 q[0].p = root;
24 q[0].depth = 1;
25 while(l < r) {
26 if(q[l].p->left == NULL && q[l].p->right == NULL) {
27 if(q[l].depth < mi) mi = q[l].depth;
28 }
29 if(q[l].p->left != NULL) {
30 q[r].p = q[l].p->left;
31 q[r].depth = q[l].depth + 1;
32 ++r;
33 }
34 if(q[l].p->right != NULL) {
35 q[r].p = q[l].p->right;
36 q[r].depth = q[l].depth + 1;
37 ++r;
38 }
39 ++l;
40 }
41 return mi;
42 }
43 };
Python DFS
2 #Runtime: 808 ms (Beats 60.23%)
3 #Memory: 94.9 MB (Beats 26.2%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 min_dep = 1000000
13 def calDepth(self, root, depth):
14 if root.left == None and root.right == None:
15 self.min_dep = min(self.min_dep, depth)
16 return
17 if root.left != None:
18 self.calDepth(root.left, depth + 1)
19 if root.right != None:
20 self.calDepth(root.right, depth + 1)
21 return
22 def minDepth(self, root):
23 """
24 :type root: TreeNode
25 :rtype: int
26 """
27 if root == None:
28 return 0
29 self.calDepth(root, 1)
30 return self.min_dep
Python BFS
2 #Runtime: 626 ms (Beats 98.87%)
3 #Memory: 92.3 MB (Beats 79.39%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def minDepth(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 if not root:
18 return 0
19 q = deque([root])
20 dep = 1
21 while q:
22 sz = len(q)
23 while sz:
24 sz -= 1
25 node = q.popleft()
26 if not node.left and not node.right:
27 return dep
28 if node.left:
29 q.append(node.left)
30 if node.right:
31 q.append(node.right)
32 dep += 1
33 return ans
]]>
2 #Runtime: 1254 ms (Beats 62.13%)
3 #Memory: 16.6 MB (Beats 33.98%)
4
5 class Solution:
6 def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
7 ans = 0
8 remain = [0] * n
9
10 def DFS(x, cnt):
11 nonlocal ans
12 if x == len(requests):
13 for i in range(n):
14 if remain[i]:
15 return
16 ans = max(ans, cnt)
17 return
18 remain[requests[x][0]] -= 1
19 remain[requests[x][1]] += 1
20 DFS(x + 1, cnt + 1)
21 remain[requests[x][0]] += 1
22 remain[requests[x][1]] -= 1
23 DFS(x + 1, cnt)
24
25 DFS(0, 0)
26 return ans
]]>
2 #Runtime: 66 ms (Beats 76.87%)
3 #Memory: 16.2 MB 錛圔eats 98.88%)
4
5 class Solution:
6 def distributeCookies(self, cookies: List[int], k: int) -> int:
7 cnt = [0] * k
8 ans = float('inf')
9 def DFS(c):
10 nonlocal ans
11 if c == len(cookies):
12 ans = min(ans, max(cnt))
13 return
14 for i in range(k):
15 cnt[i] += cookies[c]
16 DFS(c + 1)
17 cnt[i] -= cookies[c]
18 if not cnt[i]:
19 break
20
21 DFS(0)
22 return ans
]]>
2 #Runtime: 3361 ms (Beats 85.71%)
3 #Memory: 39.9 MB (Beats 14.29%)
4
5 class Solution(object):
6 def latestDayToCross(self, row, col, cells):
7 """
8 :type row: int
9 :type col: int
10 :type cells: List[List[int]]
11 :rtype: int
12 """
13 d = [[0, 1], [0, -1], [-1, 0], [1, 0]]
14 def DFS(grid, r, c):
15 if 0 <= r < row and 0 <= c < col and grid[r][c] == 0:
16 if r == row - 1:
17 return True
18 grid[r][c] = -1
19 for x in d:
20 tr = r + x[0]
21 tc = c + x[1]
22 if DFS(grid, tr, tc):
23 return True
24 return False
25
26 def ok(x):
27 grid = [[0] * col for _ in range(row)]
28 for i in range(x):
29 grid[cells[i][0] - 1][cells[i][1] - 1] = 1
30 for i in range(col):
31 if grid[0][i] == 0 and DFS(grid, 0, i):
32 return True
33 return False
34
35 l = 1
36 r = len(cells)
37 while l < r:
38 mid = (l + r) // 2 + (l + r) % 2
39 if ok(mid):
40 l = mid
41 else:
42 r = mid - 1
43 return l
44
]]>
2 #Runtime: 305 ms (Beats 78.95%)
3 #Memory: 19.6 MB (Beats 36.84%)
4
5 class Solution(object):
6 def shortestPathAllKeys(self, grid):
7 """
8 :type grid: List[str]
9 :rtype: int
10 """
11 nkey = 0
12 n, m = len(grid), len(grid[0])
13 d = [(0, 1), (1, 0), (0, -1), (-1, 0)]
14 for i in range(n):
15 for j in range(m):
16 ch = grid[i][j]
17 if ch == '@':
18 sx, sy = i, j
19 if 'a' <= ch <= 'f':
20 nkey += 1
21 q = deque([(0, sx, sy)])
22 vis = defaultdict(bool)
23 vis[(0, sx, sy)] = True
24 stp = 0
25 while q:
26 sz = len(q)
27 while sz:
28 sz -= 1
29 ky, x, y = q.popleft()
30 if ky == (1 << nkey) - 1:
31 return stp
32 for i in d:
33 tx = x + i[0]
34 ty = y + i[1]
35 if 0 <= tx < n and 0 <= ty < m:
36 tp_ky = ky
37 ch = grid[tx][ty]
38 if ch == '#':
39 continue
40 if 'a' <= ch <= 'f':
41 tp_ky |= 1 << (ord(ch) - ord('a'))
42 if 'A' <= ch <= 'F' and not (ky & (1 << (ord(ch) - ord('A')))):
43 continue
44 if not vis[(tp_ky, tx, ty)]:
45 vis[(tp_ky, tx, ty)] = True
46 q.append((tp_ky, tx, ty))
47 stp += 1
48 return -1
]]>
2 #Runtime: 590 ms (Beats 94.20%)
3 #Memory: 26.2 MB (Beats 97.10%)
4
5 class Solution(object):
6 def kSmallestPairs(self, nums1, nums2, k):
7 """
8 :type nums1: List[int]
9 :type nums2: List[int]
10 :type k: int
11 :rtype: List[List[int]]
12 """
13 fg = set()
14 ans = []
15 hp = []
16 for i in range(min(len(nums1), k)):
17 heapq.heappush(hp, (nums1[i] + nums2[0], nums1[i], nums2[0], 0))
18 while k and hp:
19 _, i, j, idx = heapq.heappop(hp)
20 ans.append([i, j])
21 if idx < len(nums2) - 1:
22 heapq.heappush(hp, (i + nums2[idx + 1], i, nums2[idx + 1], idx + 1))
23 k -= 1
24 return ans
]]>
2 #Runtime: 273 ms (Beats 91.7%)
3 #Memory: 21.5 MB (Beats 67.26%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def maxLevelSum(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 ans = []
18 q = deque([root])
19 while q:
20 sz = len(q)
21 tp = 0
22 while sz:
23 sz -= 1
24 node = q.popleft()
25 tp += node.val
26 if node.left:
27 q.append(node.left)
28 if node.right:
29 q.append(node.right)
30 ans.append(tp)
31 return max(range(len(ans)), key=ans.__getitem__) + 1
]]>
2 #Runtime: 44 ms (Beats 43.16%)
3 #Memory: 17.3 MB (Beats 71.85%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def getMinimumDifference(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 self.ans = 100000
18 self.pre_val = None
19
20 def DFS(node):
21 if not node:
22 return
23 DFS(node.left)
24 if self.pre_val is not None:
25 self.ans = min(self.ans, node.val - self.pre_val)
26 self.pre_val = node.val
27 DFS(node.right)
28
29 DFS(root)
30 return self.ans
]]>
DFS
2 #Runtime: 154 ms (Beats 66.8%)
3 #Memory: 13.6 MB (Beats 94.53%)
4
5 class Solution(object):
6 def findCircleNum(self, isConnected):
7 """
8 :type isConnected: List[List[int]]
9 :rtype: int
10 """
11 ans = 0
12 n = len(isConnected)
13 vis = [0] * n
14
15 def DFS(node):
16 vis[node] = 1
17 for i in range(n):
18 if isConnected[node][i] == 1 and not vis[i]:
19 DFS(i)
20
21 for i in range(n):
22 if not vis[i]:
23 DFS(i)
24 ans += 1
25 return ans
BFS
2 #Runtime: 156 ms (Beats 61.49%)
3 #Memory: 13.8 MB (Beats 40.4%)
4
5 class Solution(object):
6 def findCircleNum(self, isConnected):
7 """
8 :type isConnected: List[List[int]]
9 :rtype: int
10 """
11 ans = 0
12 n = len(isConnected)
13 vis = [0] * n
14 for i in range(n):
15 if not vis[i]:
16 q = deque([i])
17 vis[i] = 1
18 ans += 1
19 while q:
20 x = q.popleft()
21 for j in range(n):
22 if not vis[j] and isConnected[x][j]:
23 vis[j] = 1
24 q.append(j)
25 return ans
騫舵煡闆?br />
2 #Runtime: 178 ms (Beats 21.88%)
3 #Memory: 13.5 MB (Beats 94.53%)
4
5 class Solution(object):
6 def findCircleNum(self, isConnected):
7 """
8 :type isConnected: List[List[int]]
9 :rtype: int
10 """
11 n = len(isConnected)
12 parent = [i for i in range(n)]
13
14 def find(x):
15 if parent[x] != x:
16 parent[x] = find(parent[x])
17 return parent[x]
18
19 def union(x, y):
20 fa, fb = find(x), find(y)
21 parent[fb] = fa
22
23 for i in range(n):
24 for j in range(n):
25 if isConnected[i][j]:
26 union(i, j)
27 return len(set([find(i) for i in range(n)]))
]]>
2 #Runtime: 1174 ms (Beats 77.78%)
3 #Memory: 51.1 MB (Beats 38.10%)
4
5 class Solution(object):
6 def numOfMinutes(self, n, headID, manager, informTime):
7 """
8 :type n: int
9 :type headID: int
10 :type manager: List[int]
11 :type informTime: List[int]
12 :rtype: int
13 """
14 son = {}
15 for i in range(n):
16 if manager[i] >= 0:
17 if manager[i] not in son:
18 son[manager[i]] = [i]
19 else:
20 son[manager[i]].append(i)
21
22 def DFS(id):
23 ans = 0
24 if id not in son:
25 return 0
26 for i in son[id]:
27 ans = max(DFS(i), ans)
28 return informTime[id] + ans
29
30 return DFS(headID)
]]>
DFS錛屾敞鎰忚嫢A鑳絚over B錛孊涓嶄竴瀹氳兘cover A錛屾墍浠ユ瘡嬈¤reset vis鏁扮粍
2 #Runtime: 4068 ms (Beats 9.30%)
3 #Memory: 13.8 MB (Beats 58.14%)
4
5 class Solution(object):
6 def maximumDetonation(self, bombs):
7 """
8 :type bombs: List[List[int]]
9 :rtype: int
10 """
11
12 def In_Range(x, y):
13 if sqrt((bombs[x][1] - bombs[y][1])**2 + (bombs[x][0] - bombs[y][0])**2) <= bombs[x][2]:
14 return True
15 return False
16
17 def DFS(x):
18 for i in range(len(bombs)):
19 if not vis[i] and In_Range(x, i):
20 self.cnt += 1
21 vis[i] = 1
22 DFS(i)
23
24 ans = 0
25 for i in range(len(bombs)):
26 vis = [0] * len(bombs)
27 vis[i] = 1
28 self.cnt = 1
29 DFS(i)
30 ans = max(ans, self.cnt)
31 return ans
]]>
2 #Runtime: 528 ms (Beats 59.73%)
3 #Memory: 13.8 MB (Beats 71.4%)
4
5 class Solution(object):
6 def shortestPathBinaryMatrix(self, grid):
7 """
8 :type grid: List[List[int]]
9 :rtype: int
10 """
11 if grid[0][0] != 0:
12 return -1
13 if len(grid) == 1 and len(grid[0]) == 1:
14 return 1
15 q = deque([(0, 0, 1)])
16 grid[0][0] = 1
17 d = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]
18 while q:
19 x, y, stp = q.popleft()
20 for i in range(8):
21 tx = x + d[i][0]
22 ty = y + d[i][1]
23 if 0 <= tx < len(grid) and 0<= ty < len(grid[0]) and grid[tx][ty] == 0:
24 if tx == len(grid) - 1 and ty == len(grid[0]) - 1:
25 return stp + 1
26 grid[tx][ty] = 1
27 q.append((tx, ty, stp + 1))
28 return -1
]]>
2 #Runtime: 302 ms (Beats 92.21%)
3 #Memory: 13.9 MB (Beats 96.10%)
4
5 class Solution(object):
6 def shortestBridge(self, grid):
7 """
8 :type grid: List[List[int]]
9 :rtype: int
10 """
11 d = [[-1, 0], [1, 0], [0, 1], [0, -1]]
12 x, y = next((x, y) for x in range(len(grid)) for y in range(len(grid[0])) if grid[x][y] == 1)
13 q = deque([(x, y)])
14 boundary = set()
15 while q:
16 x, y = q.popleft()
17 grid[x][y] = -1
18 for i, j in d:
19 tx = x + i
20 ty = y + j
21 if 0 <= tx < len(grid) and 0 <= ty < len(grid[0]) and grid[tx][ty] != -1:
22 if grid[tx][ty] == 1:
23 grid[tx][ty] = -1
24 q.append((tx, ty))
25 else:
26 boundary.add((x, y))
27
28 step = 0
29 q = deque(boundary)
30 while q:
31 sz = len(q)
32 while sz > 0:
33 sz -= 1
34 x, y = q.popleft()
35 grid[x][y] = -1
36 for i, j in d:
37 tx = x + i
38 ty = y + j
39 if 0 <= tx < len(grid) and 0 <= ty < len(grid[0]) and grid[tx][ty] != -1:
40 if grid[tx][ty] == 1:
41 return step
42 else:
43 grid[tx][ty] = -1
44 q.append((tx, ty))
45 step += 1
46 return -1
47
]]>
2 #Runtime: 28 ms (Beats 72.48%)
3 #Memory: 14.9 MB (Beats 82.57%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def widthOfBinaryTree(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 q = deque([root])
18 q_idx = deque([1])
19 ans = 0
20 while q:
21 s = len(q)
22 for i in range(s):
23 node = q.popleft()
24 x = q_idx.popleft()
25 if i == 0:
26 tp_min = x
27 if i == s - 1:
28 tp_max = x
29 if node.left:
30 q.append(node.left)
31 q_idx.append(2 * x - 1)
32 if node.right:
33 q.append(node.right)
34 q_idx.append(2 * x)
35 ans = max(ans, tp_max - tp_min + 1)
36 return ans
]]>
2 #Runtime: 366 ms (Beats 100%)
3 #Memory: 64.2 MB (Beats 66.67%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def longestZigZag(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 self.ans = 0
18
19 def DFS(node, pre, length):
20 if not node:
21 return
22 if length > self.ans:
23 self.ans = length
24 if pre == -1:
25 DFS(node.left, 0, length + 1)
26 DFS(node.right, 1, length + 1)
27 elif pre == 0:
28 DFS(node.left, 0, 1)
29 DFS(node.right, 1, length + 1)
30 else:
31 DFS(node.left, 0, length + 1)
32 DFS(node.right, 1, 1)
33
34 DFS(root, -1, 0)
35 return self.ans
]]>
2 #Runtime: 3256 ms (Beats 12.50%)
3 #Memory: 202.1 MB (Beats 12.50%)
4
5 class Solution(object):
6 def largestPathValue(self, colors, edges):
7 """
8 :type colors: str
9 :type edges: List[List[int]]
10 :rtype: int
11 """
12 graph = defaultdict(list)
13 for x, y in edges:
14 graph[x].append(y)
15 vis = set()
16 path = set()
17 ans = 0
18 n = len(colors)
19 self.has_circle = False
20 cnt = [[0] * 26 for _ in range(n)]
21 def DFS(x):
22 if x in path:
23 self.has_circle = True
24 if x in vis:
25 return 0
26 vis.add(x)
27 path.add(x)
28 idx = ord(colors[x]) - ord('a')
29 cnt[x][idx] = 1
30 for y in graph[x]:
31 DFS(y)
32 if self.has_circle == True:
33 return float('inf')
34 for ch in range(26):
35 cnt[x][ch] = max(cnt[x][ch], (1 if ch == idx else 0) + cnt[y][ch])
36 path.remove(x)
37 return max(cnt[x])
38
39 for i in range(n):
40 ans = max(ans, DFS(i))
41 return -1 if ans == float('inf') else ans
]]>
2 #Runtime: 41 ms (Beats 39.30%)
3 #Memory: 13.8 MB (Beats 37.71%)
4
5 """
6 # Definition for a Node.
7 class Node(object):
8 def __init__(self, val = 0, neighbors = None):
9 self.val = val
10 self.neighbors = neighbors if neighbors is not None else []
11 """
12
13 class Solution(object):
14 def cloneGraph(self, node):
15 """
16 :type node: Node
17 :rtype: Node
18 """
19 def DFS(node, cloned_graph):
20 if node not in cloned_graph:
21 cloned_graph[node] = Node(node.val)
22 for nr in node.neighbors:
23 cloned_graph[node].neighbors.append(DFS(nr, cloned_graph))
24 return cloned_graph[node]
25 if node == None:
26 return None
27 return DFS(node, {})
]]>
2 #Runtime: 691 ms (Beats 37.84%)
3 #Memory: 75.3 MB (Beats 20.27%)
4
5 class Solution(object):
6 def numEnclaves(self, grid):
7 """
8 :type grid: List[List[int]]
9 :rtype: int
10 """
11 self.dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]
12 n = len(grid)
13 m = len(grid[0])
14
15 def DFS(x, y):
16 grid[x][y] = 0
17 self.tp += 1
18 for dx, dy in self.dir:
19 tx = x + dx
20 ty = y + dy
21 if 0 <= tx < n and 0 <= ty < m and grid[tx][ty]:
22 DFS(tx, ty)
23 elif tx < 0 or ty < 0 or tx >= n or ty >= m:
24 self.fg = False
25
26
27 self.vis = [[0] * m for _ in range(n)]
28 self.ans = 0
29 for i in range(1, n - 1):
30 for j in range(1, m - 1):
31 if grid[i][j] == 1:
32 self.fg = True
33 self.tp = 0
34 DFS(i, j)
35 if self.fg == True:
36 self.ans += self.tp
37 return self.ans
]]>
2 #Runtime: 103 ms (Beats 49.4%)
3 #Memory: 14 MB (Beats 37.50%)
4
5 class Solution(object):
6 def closedIsland(self, grid):
7 """
8 :type grid: List[List[int]]
9 :rtype: int
10 """
11 self.dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]
12 n = len(grid)
13 m = len(grid[0])
14
15 def DFS(x, y):
16 grid[x][y] = 1
17 for dx, dy in self.dir:
18 tx = x + dx
19 ty = y + dy
20 if 0 <= tx < n and 0 <= ty < m and not grid[tx][ty]:
21 DFS(tx, ty)
22 elif tx < 0 or ty < 0 or tx >= n or ty >= m:
23 self.fg = False
24
25
26 self.vis = [[0] * m for _ in range(n)]
27 ans = 0
28 for i in range(1, n - 1):
29 for j in range(1, m - 1):
30 if grid[i][j] == 0:
31 self.fg = True
32 DFS(i, j)
33 if self.fg == True:
34 ans += 1
35 return ans
]]>
2 #Runtime: 22 ms (Beats 58.42%)
3 #Memory: 13.4 MB (Beats 71.73%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def isCompleteTree(self, root):
13 """
14 :type root: TreeNode
15 :rtype: bool
16 """
17 gap_between_nodes = False
18 q = deque([root])
19 while q:
20 s = len(q)
21 while s:
22 s -= 1
23 node = q.popleft()
24 if not node:
25 gap_between_nodes = True
26 else:
27 if gap_between_nodes:
28 return False
29 q.append(node.left)
30 q.append(node.right)
31 return True
]]>