Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking for connections in a 2d array
    text
    copied!<p>So I have a square 2d array. The dimensions will be nxn. The array contains only zeros and ones. More specifically it will contain exactly n 1's. I need to check if all the 1's are "connected" spatially. Example: </p> <pre><code> 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 </code></pre> <p>This is invalid. Diagonal connections do not count. So far my code will check the array but only for lone single 1's. If the 1's are split into two groups of two for example, my check would miss it. Any advice is appreciated. Here is my code so far:</p> <pre><code> int conected(char *stringptr) { int n=sqrt(strlen(stringptr)); int i=0; int j=0; int k=0; char array2d[n][n]; for (j=0;j&lt;n;j++) { for (i=0;i&lt;n;i++) { array2d[j][i]=stringptr[k]; k++; } } for (j=0;j&lt;n;j++) { for (i=0;i&lt;n;i++) { if (array2d[j][i]=='1') { if (i==0 &amp;&amp; j==0) {//special case for first element if ((array2d[j][i+1]=='0') &amp;&amp; (array2d[j+1][i]=='0')) { return 0; } } else if ((j==0) &amp;&amp; (i!=(n-1))) {//top row if ((array2d[j][i+1]=='0') &amp;&amp; (array2d[j+1][i]=='0') &amp;&amp; (array2d[j][i-1]=='0')) { return 0; } } else if ((j==0) &amp;&amp; (i==(n-1))) {// right corner if ((array2d[j+1][i]=='0') &amp;&amp; (array2d[j][i-1]=='0')) { return 0; } } else if ((i==0) &amp;&amp; (j!=(n-1))) { //left column if ((array2d[j][i+1]=='0') &amp;&amp; (array2d[j+1][i]=='0') &amp;&amp; (array2d[j-1][i]=='0')) { return 0; } } else if ((i==(n-1)) &amp;&amp; (j!=(n-1))) {// right column if ((array2d[j][i-1]=='0') &amp;&amp; (array2d[j+1][i]=='0') &amp;&amp; (array2d[j-1][i]=='0')) { return 0; } } else if ((i==0) &amp;&amp; (j==(n-1))) {//bottom left corner if ((array2d[j][i+1]=='0') &amp;&amp; (array2d[j-1][i]=='0')) { return 0; } } else if ((j==(n-1)) &amp;&amp; (i!=(n-1))) {//bottom row if ((array2d[j][i+1]=='0') &amp;&amp; (array2d[j-1][i]=='0') &amp;&amp; (array2d[j][i-1]=='0')) { return 0; } } else if ((j==(n-1)) &amp;&amp; (i==(n-1))){ //bottom right corner if ((array2d[j][i-1]=='0') &amp;&amp; (array2d[j-1][i]=='0')) { return 0; } } else { if ((array2d[j][i-1]=='0') &amp;&amp; (array2d[j+1][i]=='0') &amp;&amp; (array2d[j-1][i]=='0') &amp;&amp; (array2d[j][i+1]=='0')) { return 0; } } } } } return 1; </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload