Handle borders in the scanning algorithm