Count zero segments in matrix

Given a n x n matrix consisting of 0 and 1, count the number of segments with 0. A segment is connected cells which are directly adjacent on same row or column.

For example, in below matrix, the zero segments are 4.

{0, 1, 1, 1, 1},
{0, 1, 1, 0, 0},
{1, 0, 1, 0, 1},
{0, 0, 1, 1, 1},
{0, 1, 1, 1, 0}

开始感觉BFS应该可以解,不过后来绕晕了,电话上跟自己做题总是不一样的,虽然不紧张。

DP可解吗?写了一个错误的DP解法,有没有正确的解法呢?事实证明BFS/DFS是可解的,也比较简单。用代码来说话。

// matrix.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

// Wrong solution
int getZeroSegmentsDP(vector<vector<int>> &matrix) {
	int size = matrix.size();
	if (size <= 0) {
		return -1;
	}

	int count = 0;
	vector<bool> dp(size+1, false);
	for (int i = 0; i < size; ++i) {
		for (int j = 0; j < size; ++j) {
			if (matrix[i][j] == 0) {
				if (!dp[j] && !dp[j+1]) {
					++count;
				}
				dp[j+1] = true;
			}
			else {
				dp[j+1] = false;
			}
		}
	}

	return count;
}

void fillMatrix(vector<vector<int>> &matrix, int row, int col) {
	matrix[row][col] = 2;
	if (row - 1 >= 0 && matrix[row-1][col] == 0) {
		fillMatrix(matrix, row-1, col);
	}
	if (row + 1 < matrix.size() && matrix[row+1][col] == 0) {
		fillMatrix(matrix, row+1, col);
	}
	if (col - 1 >= 0 && matrix[row][col-1] == 0) {
		fillMatrix(matrix, row, col-1);
	}
	if (col + 1 < matrix.size() && matrix[row][col+1] == 0) {
		fillMatrix(matrix, row, col+1);
	}
}

// Correct solution
int getZeroSegmentsDFS(vector<vector<int>> &matrix) {
	int size = matrix.size();
	if (size <= 0) {
		return -1;
	}

	// Change the cell with 0 to 2
	int count = 0;
	for (int i = 0; i < size; ++i) {
		for (int j = 0; j < size; ++j) {
			if (matrix[i][j] == 0) {
				fillMatrix(matrix, i, j);
				++count;
			}
		}
	}

	// Restore the matrix
	for (int i = 0; i < size; ++i) {
		for (int j = 0; j < size; ++j) {
			if (matrix[i][j] > 1) {
				matrix[i][j] = 0;
			}
		}
	}

	return count;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int array2d[][5] = {
		{0, 1, 1, 1, 1},
		{0, 1, 0, 0, 0},
		{1, 0, 1, 0, 1},
		{0, 0, 0, 0, 1},
		{0, 1, 1, 1, 0}
	};
	vector<vector<int>> matrix(5, vector<int>(5));
	for (int i = 0; i < 5; ++i) {
		matrix[i] = vector<int>(array2d[i], array2d[i] + sizeof(array2d[i])/sizeof(int));
	}

	cout << "The zero segments by DP method are: " << getZeroSegmentsDP(matrix) << endl;
	cout << "The zero segments by DFS method are: " << getZeroSegmentsDFS(matrix) << endl;

	// Print the matrix
	for (int i = 0; i < matrix.size(); ++i) {
		for (int j = 0; j < matrix[i].size(); ++j) {
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}

	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值