I know in order to compensate with change in speed but how does Light actually know which path is less dense or more dense?
Light doesn't actually 'know' which path is the shortest. In the quantum mechanical description, light actually takes all paths between point A and point B. It turns out that the phase of different paths adds up in such a way that the classical path corresponds to the one in which time taken is the least. For a more detailed explanation read QED: The Strange Theory of Light and Matter by Richard Feynman or section 26-6 of http://www.feynmanlectures.caltech.edu/I_26.html