added visited optimization