counting edges algorithm