package before.test.problem1

class Solution {

    fun solution(histogram: Array<IntArray>): Int {

        var result = 1
        val height = histogram.size
        val width = histogram[0].size
        var histogramConversionAxis = Array(width) { IntArray(height) }

        histogramConversionAxis = setHistogramConversionAxis(histogram, histogramConversionAxis, width, height)

        for (row in histogramConversionAxis.indices) {
            var possibleGraphHeight: Int
            var firstZero = histogramConversionAxis[row].indexOf(0)

            if (firstZero == -1) firstZero = height

            possibleGraphHeight = find(firstZero, histogramConversionAxis, row)
            result *= possibleGraphHeight
        }
        return result
    }

    private fun setHistogramConversionAxis(
        histogram: Array<IntArray>,
        histogramConversionAxis: Array<IntArray>,
        width: Int,
        height: Int
    ): Array<IntArray> {
        for (row in histogram.indices) {
            for (column in histogram[row].indices) {
                histogramConversionAxis[width - column - 1][height - row - 1] = histogram[row][column]
            }
        }
        return histogramConversionAxis
    }

    private fun find(
        firstZero: Int,
        histogramConversionAxis: Array<IntArray>,
        row: Int
    ): Int {
        var possibleGraphHeight = 1
        for (column in firstZero - 1 downTo 0) {
            if (histogramConversionAxis[row][column] == 1) break
            if (histogramConversionAxis[row][column] == 2) possibleGraphHeight += 1
        }
        return possibleGraphHeight
    }
}
