Algebraic formalism is proposed to describe the neutrino oscillations in heterogeneous media when traditional approaches based on perturbation theory are inefficient. Exact solutions of corresponding equations are obtained for models of variations in the density of a medium occurring at the Sun and the Earth.