ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
from collections import deque
def islands(g):
R, C = len(g), len(g[0])
seen = set()
cnt = 0
for r in range(R):
for c in range(C):
if g[r][c] == '1' and (r, c) not in seen:
cnt += 1
q = deque([(r, c)])
seen.add((r, c))
while q:
x, y = q.popleft()
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < R and 0 <= ny < C and g[nx][ny] == '1' and (nx, ny) not in seen:
seen.add((nx, ny))
q.append((nx, ny))
return cnt
print(islands(['11000', '11011', '00100', '00011']))- A. 3
- B. 5
- C. 2
- D. 4
Correct answer: D. 4
Each BFS from an unseen land cell finds one whole island. The lone cell at (2,2) touches no other land, so the four islands are the top-left block, the pair in row 1, the single cell and the pair in row 3.
More Python Programming questions
- What is printed? python import heapq def refuel(target, start, stations): h = [] i = 0 fuel = start stops = 0 while fuel < target: while i…
- What is printed? python import heapq def jobs(items): items = sorted(items, key=lambda x: x[0]) h = [] for d, p in items…
- What is printed? python try: print(sorted([3, None, 1])) except TypeError: print('TypeError') print(max(['b', 'a'], key=str.upper)…
- What is printed? python s = 'hello' try: s[0] = 'j' except TypeError: print('immutable') t = s.replace('h', 'j') print(t, s)
- What is printed? python print(1020 / 1019, 1020 // 1019, 264 % 1000, 1020 == 1e20)
- What is printed? python calls = [] def f(x): calls.append(x) return x 2 m = map(f, [1, 2, 3]) print(calls) first = next(m) print(calls…