Group of 1s in a Matrix

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值