Introduction
It is my mock interview algorithm called Island count. I was so excited to work with a peer who is from Israel this morning 10:00 AM. The peer told me that it is better to write an iterative solution.
Code review
I had to follow the advise from the peer, and then I decided to write a queue to apply breadth first search to visit neighbors, mark visited.
Here is my C# code passing all test cases.
The instruction to play mock interview nicely
I have worked on this algorithm so many times. I know how to train myself one more time nice and easy, get more experience how to write readable code, practice one more time to explain the algorithm and talk about ideas with a peer.
First few minutes, I will write down the matrix using example 5 x 5 matrix, and go over row by row from left to right starting from position (0, 0). If I find the first one, I will mark it visited, and then use DFS/ BFS to visit all neighbors as elements in the same island. I will increment island count variable one. I will mark the first island using char 'A', next island using 'B', likewise. I will apply the same analysis twice, using -1 to mark first two islands A and B, and then just quickly apply C, D, E, F for the rest of islands.
After that, I will ask the peer's advice to choose DFS or BFS. Give him/ her a choice, and follow the advice. I am willing to write any solution, but I do not want to stick on one solution, I like to practice any solution if need.
This time the peer told me that I should not use recursive function, it is written to write iterative solution in mock interview platform for interviewer. So I have to follow the advice, decide to write the iterative solution.
I thought about using for loops, and then decided to write a queue. Since it is the only way I can apply BFS without using recursive function, otherwise I cannot handle the neighbors just using loops. Data structure queue is definitely needed.
Beautiful code
It is not tough for me to write readable code using Queue, and apply BFS algorithm. I have practiced similar algorithm so many times last 12 months.
I learn how to write readable code last 18 months.
Give credit to the code reviewer, here is the link.
Here is the blog about my past practice. I need to get organized and then I can review what each my past practice and see how good I am getting.
No comments:
Post a Comment