You are on page 1of 13

Exercise A

2022312834
Jiwon Choi
Problem explanation
• There is a N*N matrix with rows and columns sorted in
ascending order, respectively.

• How do you find k efficiently in the N*N matrix?


Solution explanation
• If you start searching sequentially at (0,0) or (N-1,N-1), you
should search all the elements in the worst case.

start 1 5 6 7 25 k 1 5 6 7 25

2 6 8 16 27 2 6 8 16 27

3 7 14 18 28 3 7 14 18 28

4 8 15 21 30 4 8 15 21 30

10 11 20 23 50 k 10 11 20 23 50 start
Solution explanation
! !
• Therefore, start the search at ( , ).
" "
• Example : k=27, N=5
1 5 6 7 25

2 6 8 16 27 k

3 7 14 18 28

4 8 15 21 30

10 11 20 23 50
Solution explanation
• Push (2,2) into the Stack.

1 5 6 7 25

2 6 8 16 27 k

3 7 14 18 28

4 8 15 21 30

10 11 20 23 50 (2, 2)
Solution explanation
• Pop the top data, (2,2) from the Stack.
• 14 is smaller than k → search for the values on the right and
bottom (to find bigger numbers).

1 5 6 7 25

2 6 8 16 27 k
14 < k
3 7 14 18 28

4 8 15 21 30

10 11 20 23 50 (2, 2)
Solution explanation
• Push (3,2) and (2,3) into the Stack.

1 5 6 7 25

2 6 8 16 27 k

3 7 14 18 28

4 8 15 21 30 (2, 3)

10 11 20 23 50 (3, 2)
Solution explanation
• Pop the top data, (2,3) from the Stack.
• 18 is smaller than k → search for the values on the right and
bottom.

1 5 6 7 25

2 6 8 16 27 k
18 < k
3 7 14 18 28

4 8 15 21 30

10 11 20 23 50 (3, 2) (2, 3)
Solution explanation
• Push (3,3) and (2,4) into the Stack.

1 5 6 7 25

2 6 8 16 27 k

3 7 14 18 28 (2, 4)
4 8 15 21 30 (3, 3)

10 11 20 23 50 (3, 2)
Solution explanation
• Pop the top data, (2,4) from the Stack.
• 28 is bigger than k → search for the values on the left and
top (to find smaller numbers).

1 5 6 7 25

2 6 8 16 27 k
28 > k
3 7 14 18 28

4 8 15 21 30 (3, 3)

10 11 20 23 50 (3, 2) (2, 4)
Solution explanation
• Push (1,4) and (2,3) into the Stack.

1 5 6 7 25

2 6 8 16 27 k (2, 3)
3 7 14 18 28 (1, 4)
4 8 15 21 30 (3, 3)

10 11 20 23 50 (3, 2)
Solution explanation
• Pop the top data, (2,3) from the Stack.
• (2,3) has already been visited → Pass

1 5 6 7 25

2 6 8 16 27 k
already visited
3 7 14 18 28 (1, 4)
4 8 15 21 30 (3, 3)

10 11 20 23 50 (3, 2) (2, 3)
Solution explanation
• Pop the top data, (1,4) from the Stack.
• 27 is the k → End of the steps

1 5 6 7 25

2 6 8 16 27 k
27 = k
3 7 14 18 28

4 8 15 21 30 (3, 3)

10 11 20 23 50 (3, 2) (1, 4)

You might also like