Finding the number of squares by connected coordinates
Let $b(p, \ell)$ be a boolean value denoting whether the horizontal segment whose left endpoint is $p$ and whose length is $\ell$ exists. Then the values of $b(p,\ell)$ for all possible $p$ and $\ell$ can be computed in $O(n^3)$ recursively using the fact that


  $b(p,\ell)$ is true iff $b(p,\ell-1)$ is true and $b(p+\ell-1,1)$ is true where $p+\ell-1$ denotes the point on the right side of $p$ and the distance between them is $\ell-1$.


Here $n$ is the length of the grid.

Similarly, you can do the same thing for vertical segments.

Now you can check each possible square by checking its four edge segments. The whole running time is $O(n^3)$.



As j_random_hacker said in the comment, 


  You can drop the space usage to $O(n^2)$ by instead calculating the length $w(p)$ of the longest horizontal segment having left endpoint $p$ for all $p$. Then $b(p,\ell)=(w(p)\ge\ell)$.