中兴上机笔试题:计算相连的房屋块数

        中兴的简历因事情太多忘记注册了,看了同学做的两道编程题,感觉都很基础,今天一个师弟拿着一到编程题来跟我讨论。


题目:就是在一个网格子上,如果有房子,则该点设置为1,没有则设置为0,如果上下左右相邻的房子,则算做是一个片区的房子。对角上的(1,1)则不算。看了一眼题目,很简单的嘛。 想了个粗暴的算法,遍历每个网格点,如果为1,则用一个队列将与该点连接的所有节点设置为0。然而就是这道简单的题目,花了快一个小时来调试。好弱QAQ.主要原因还是STL用的不够熟练,取deque最后一个元素的函数是back(),随便找点资料,用了反向迭代器去取这个元素,导致取得元素一直不正确。看来还的深入探究下deque删除元素的机理啊。这个等有时间去看看。先贴下代码

#ifndef _BLOCK_H_
#define _BLOCK_H_

#include <iostream>
#include <deque>
#include <stdio.h>

using namespace std;

#define N 10

int  cells[10][10] = { 
{ 1, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 1, 1, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 1, 0, 1, 1, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 1, 1, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
};

struct Pos
{
	int x;
	int y;
};

int  diff[4][2] = { {0,-1},
					{1, 0},
					{0, 1},
					{-1,0}
				 };

int Clear(int cells[][N], int i, int j);


int CalCell(int cells[][N], int cols, int rows)
{
	int count = 0;

	for (int i = 0; i < rows; i++)
		for (int j = 0; j < cols; j++)
			if (cells[i][j] == 1)
			{
				count = count + 1;
				Clear(cells,i,j);
			}
	 
	return count;
}


int Clear(int cells[][N], int i, int j)
{
	int nx, ny;
	Pos p; Pos n_p;
	p.x = i, p.y = j;
	deque<Pos>block;

	// set current pos to zero
	cells[i][j] = 0;

	//push all recent pos to deque
	do
	{
		if (!block.empty())
			block.pop_front();
		
		for (int i = 0; i < 4; i++)
		{
			nx = p.x + diff[i][0]; ny = p.y + diff[i][1];
			if ((nx<N && nx >= 0) && (ny<N && ny >= 0) && cells[nx][ny] == 1)
			{
				n_p.x = nx, n_p.y = ny;
				block.push_back(n_p);
			}
		}

		if (!block.empty())
		{
			p = block.front();
			cells[p.x][p.y] = 0;
		}

	}while (!block.empty());

	return 0;
}

#endif


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值