Algorithm is one the fundamental components that a programmer should master. But every time I read a book about it, I see intrusive instructions about how to solve a problem using several algorithms. Well they just tell you that you should use this and that. Sure, they are brilliant ideas, but how do those ideas come up? If we do not know this process, it is hard to say we have really learned.

I’ve been reading the book “How to solve it” by George Pólya. It is a great book that shows you how to approach a problem using various steps. You can ask about certain questions and answer them to get a better chance to obtain the final solution. Although this book is about mathematics, I think it also applies for algorithms or even just problems in general. So I’d like to write the conversation I made myself to show the process of how we get an algorithm without giving intrusive instructions. These are just my humble ideas and suggestions are always welcome.

====================================================================

**Q: What is the unknown? What is our goal?**

**Q: What are the conditions?**

**Q: What does it mean by “in place”?**

**Q: What are the data?**

**Q: Can you give me some examples?**

**Q: Have you seen it before? Or have you seen a similar problem in a slightly different form?**

**Q: And what is that?**

**Q: Do you think you can use it including its result and method?**

**Q: OK, let’s look at your example here. Suppose you rotate the 3-by-3 matrix. What will you get in the end?**

**Q: What if you switch elements across the diagonal? What will you get?**

**Q: So how far is this matrix to the expected matrix?**

**Q: Correct. What steps did we do to rotate the matrix?**

**Q: Good. But is it also true for a 4-by-4 matrix?**

**Q: Nice. Now you have a plan. Implement it carefully.**

**If you do not know a similar problem (like the switch elements across the diagonal), ask yourself what kind of switching operation can you do on a matrix?**(Similar to the question: What operation can you do with bits?)

**If you cannot do it in one step, try to do it in several steps.**

## One thought on “Rotate an n-by-n matrix 90 degrees clockwise in place — A conversation”