Connected component labeling in matrix
<p>I'm trying to do the following
Given the following matrix (where 1's are empty cells and 0's are obstacles):<br>
0 0 1 1<br>
1 0 0 0<br>
1 0 1 1<br>
1 1 0 0<br>
I want it to become like this:<br>
0 0 1 1<br>
2 0 0 0<br>
2 0 2 2<br>
2 2 0 0</p>

<p>What I need to do is to label all connected components (free spaces).
What I already tried to do is to write a function called isConnected() which takes indexes of two cells and checks if there is a connected path between them. And by repeating this function n^2 times on every empty cell on the matrix I can label all connected spaces. But as this algorithm has a bad time complexity (n^2*n^2*O(isConnected())) I prefer to use something else.<br>
I hope these pictures will explain better what I'm trying to accomplish:  </p>

<p><a href="https://i.stack.imgur.com/lSBBO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lSBBO.png" alt="enter image description here"></a></p>

<p><a href="https://i.stack.imgur.com/BLAdn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BLAdn.png" alt="enter image description here"></a>  </p>

<p><a href="https://i.stack.imgur.com/yCwNh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yCwNh.png" alt="enter image description here"></a></p>