• + 0 comments

    A solution in C# that is more slightly more optimized than the rest I've seen here. Because of how a cavity is defined in this, there are two conditions where you can skip evaluating the four adjacent locations:

    1. If the element preceding the current one in this row was a cavity, this one cannot be. We can use this to skip the next position by incrementing our loop an additional time while replacing the character in the string.
    2. If the element at this position in the previous row was a cavity, this one cannot be. We can take advantage of the short-circuit evaluation of C# to reduce the number of comparison operations by placing the [i - 1] [j] check first, as that will always be false if the cell at that position was changed to 'X'. (Note: not all languages use short-circuit evaluation, so for some languages this will change nothing)

    Combined, these two changes can remove up to approximately 3.5 * ((N - 2) ^ 2) / 2 comparison operations from our execution time!

    public static List<string> cavityMap(List<string> grid)
        {
            for (int i = 1; i < grid.Count - 1; i++)
            {
                for (int j = 1; j < grid[i].Length - 1; j++)
                {
                    if (grid[i].ElementAt(j) > grid[i - 1].ElementAt(j) &&
                        grid[i].ElementAt(j) > grid[i + 1].ElementAt(j) &&
                        grid[i].ElementAt(j) > grid[i].ElementAt(j - 1) &&
                        grid[i].ElementAt(j) > grid[i].ElementAt(j + 1))
                    {
                        
                        grid[i] = grid[i].Substring(0, j) + "X" + grid[i].Substring(++j);
                    }
                }
            }
            return grid;
        }