memoizing the neighbors function over graphs