Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'll first give you the code and then explain it a bit:</p> <pre class="lang-cpp prettyprint-override"><code>// direction vectors const int dx[] = {+1, 0, -1, 0}; const int dy[] = {0, +1, 0, -1}; // matrix dimensions int row_count; int col_count; // the input matrix int m[MAX][MAX]; // the labels, 0 means unlabeled int label[MAX][MAX]; void dfs(int x, int y, int current_label) { if (x &lt; 0 || x == row_count) return; // out of bounds if (y &lt; 0 || y == col_count) return; // out of bounds if (label[x][y] || !m[x][y]) return; // already labeled or not marked with 1 in m // mark the current cell label[x][y] = current_label; // recursively mark the neighbors for (int direction = 0; direction &lt; 4; ++direction) dfs(x + dx[direction], y + dy[direction], current_label); } void find_components() { int component = 0; for (int i = 0; i &lt; row_count; ++i) for (int j = 0; j &lt; col_count; ++j) if (!label[i][j] &amp;&amp; m[i][j]) dfs(i, j, ++component); } </code></pre> <p>This is a common way of solving this problem.</p> <p>The direction vectors are just a nice way to find the neighboring cells (in each of the four directions).</p> <p>The <b>dfs</b> function performs a <em>depth-first-search</em> of the grid. That simply means it will visit all the cells reachable from the starting cell. Each cell will be marked with <strong>current_label</strong></p> <p>The <strong>find_components</strong> function goes through all the cells of the grid and starts a component labeling if it finds an unlabeled cell (marked with 1).</p> <p>This can also be done iteratively using a stack. If you replace the stack with a queue, you obtain the <em>bfs</em> or <em>breadth-first-search</em>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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