Python – Calculating words in matrix – contest problem

Today I was looking into the following problem for word counter in python from Hack Bulgaria:

You are given a rectangular table filled with characters and a word. Your task is to count the occurrences of the word in the table. The word can be found horizontally, vertically and across both left to right and right to left.


As you see in the picture, you have to look for the word in 8 directions – two diagonals, once per line and once per row, left to right and right to left. Which is pretty much coding, if you start doing it like this. So, I was thinking what a good programmer should do. Then I have decided that a good programmer would outsource it, so I have started to think what a mediocre programmer would do. Thus, I have decided that I actually need not more than 4 operations – I do not need to look for left to right and right to left separately, but I can reverse the word and look the reversed word as well.

After understanding this, I have tought of reversing the matrix in a way that the rows become columns and columns become rows. Thus, I can do two types of search with one function. With the diagonals, I have used something similar – mirroring the matrix and repeating the search in the mirrored matrix. Thus, with 2 procedures I have managed to do the 8 searches in a good way! 🙂

So far so good, here comes the code:

Enjoy it!


Tagged with: , , ,