it could be as bad as n*m. if (m) is dense matrix, then this is (n)², so this algorithm ended up being in cubed again, but if it's a sparse matrix, so the number of edges is linear like in a planar graph, for example, then this is (n)² which is actually a lot better.