Search code examples
cperformancematrixneighbourscoding-efficiency

Checking the neighbours of a cell value from a matrix


I have a matrix filled with * and -, where * represents a virus and - a free spot for a virus, I have to check in my matrix the neighbours of every virus, a valid neighbour is another virus and not a free spot, in order to establish their number. The neighbours I have to check are [row + 1][col], [row - 1][col], [row][col + 1] and [row][col - 1], in total four neighbours. I made a function to check and cover all the cases, for example if the element that I am checking is one of the corners of the matrix. I came up with a really long 80 lines function that has a lot of if statements. Is there an efficient way(meaning the number of lines) to check all this besides having to write like 20 if statements?

https://pastebin.com/2f7YpreZ Here is the code I've written


Solution

  • What you could do is to merge if statements that lead to the same results. This will lead to shorter (and more readable) code, and can boost performance in certain cases.

    So for example if you have:

    if([row - 1][col])
        // do A
    else if([row][col + 1])
        // do B
    else if([row + 1][col])
        // do A
    

    then you could write it as such:

    if([row - 1][col] || [row + 1][col])
        // do A
    else if([row][col + 1])
        // do B
    

    Do this, and you feel that your code needs further improvements, please post at Code Review.