Problem: Given a matrix with 1s and 0s, please find the number of groups of 1s. A group is defined by horizontally or vertically adjacent 1s. For example, there are four groups of 1s in Figure 1 which are drawn with different colors.
| Figure 1: A matrix with four groups of 1s. Different groups are drawn with different colors. |
/* Copyleft: Ming Lin <minggr@gmail.com> */
#include <stdio.h>
int *position(int *data, int col_max, int row, int col)
{
int i = (col_max + 1) * row + col;
return &data[i];
}
void flood_fill_recursive(int *data, int row_max, int col_max, int row, int col)
{
int *p = position(data, col_max, row, col);
int up, down, left, right;
if (*p == 0)
return;
*p = 0;
up = row - 1;
if (up >= 0)
flood_fill_recursive(data, row_max, col_max, up, col);
down = row + 1;
if (down <= row_max)
flood_fill_recursive(data, row_max, col_max, down, col);
left = col - 1;
if (left >= 0)
flood_fill_recursive(data, row_max, col_max, row, left);
right = col + 1;
if (right <= col_max)
flood_fill_recursive(data, row_max, col_max, row, right);
}
void flood_fill_stack(int *data, int row_max, int col_max, int row, int col)
{
int stack[10];
int top = 0;
int up, down, left, right;
int i;
stack[top++] = row*(col_max+1) + col;
while (top) {
top--;
i = stack[top];
row = i / (col_max + 1);
col = i % (col_max + 1);
printf("[%d, %d]:\n", row, col);
data[i] = 0;
up = row - 1;
if (up >= 0) {
i = up*(col_max+1) + col;
if (data[i] == 1) {
stack[top++] = i;
printf(" [%d, %d]\n", up, col);
}
}
down = row + 1;
if (down <= row_max) {
i = down*(col_max+1) + col;
if (data[i] == 1) {
stack[top++] = i;
printf(" [%d, %d]\n", down, col);
}
}
left = col - 1;
if (left >= 0) {
i = row*(col_max+1) + left;
if (data[i] == 1) {
stack[top++] = i;
printf(" [%d, %d]\n", row, left);
}
}
right = col + 1;
if (right <= col_max) {
i = row*(col_max+1) + right;
if (data[i] == 1) {
stack[top++] = i;
printf(" [%d, %d]\n", row, right);
}
}
}
}
int group_of_1s(int *data, int row_max, int col_max)
{
int row, col;
int *p;
int total = 0;
for (row = 0; row <= row_max; row++) {
for (col = 0; col <= col_max; col++) {
p = position(data, col_max, row, col);
if (*p == 1) {
total++;
//flood_fill_recursive(data, row_max, col_max, row, col);
flood_fill_stack(data, row_max, col_max, row, col);
}
}
}
return total;
}
int main()
{
int data[] = {1, 1, 0, 0, 1,
1, 0, 0, 1, 0,
1, 1, 0, 1, 0,
0, 0, 1, 0, 0};
int row_max = 3;
int col_max = 4;
printf("group_of_1s: %d\n", group_of_1s(data, row_max, col_max));
return 0;
}

被折叠的 条评论
为什么被折叠?



