ProgrammingHardAccenture · Cognizant pattern
What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.)
What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.)
Integer grid[4][4] = {{1,1,0,0},{1,1,0,0},{0,0,1,0},{0,0,0,1}}
Boolean visited[4][4] = all false
Integer count = 0
Function dfs(Integer r, Integer c)
if (out of bounds or visited[r][c] or grid[r][c] == 0)
return
end if
visited[r][c] = true
dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1)
End Function
for (each r from 0 to 3)
for (each c from 0 to 3)
if (grid[r][c] == 1 and not visited[r][c])
count = count + 1
dfs(r, c)
end if
end for
end for
Print count- A. 2
- B. 4
- C. 3
- D. 1
Correct answer: C. 3
There are three separate connected groups of 1s: the 2x2 block in the top-left, the single 1 at (2,2), and the single 1 at (3,3) -- 3 islands total.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (summing positive and negative matrix entries separately)? Integer mat[3][3] = {{1…
- What will be the output of the following pseudocode (counting distinct pairs whose difference is k)? (Arrays are indexed from 0.) Integer…
- What will be the output of the following pseudocode (2x2 matrix multiplication)? Integer A[2][2] = {{1, 2}, {3, 4}} Integer B[2][2] = {{5…
- What will be the output of the following pseudocode (binary string to decimal)? String bits = "110101" Integer val = 0 for (each b in…
- What will be the output of the following pseudocode (finding the 1-based position of the rightmost set bit)? (All variables are integers…
- What will be the output of the following pseudocode (checking if s3 is an interleaving of s1 and s2, via dynamic programming)? Function…