算法 棋盘棋子问题

题干:一个10*10的棋盘上下了某些棋子,若棋子的上下左右有棋子,则这些棋子被称为一个块,求一种算法,得到棋盘上有几个块。

我这种思路是使用递归求解

思路就是

1.棋盘上的每一个点有两个标志位,一个代表是否有棋子,一个代表是否遍历过。

2.遍历棋盘上每一个点,遍历之前先把当前点的遍历状态置成遍历过。

3.若上下左右有棋子就递归,而后把当前点的棋子删掉。

4.最后遍历棋盘上还剩几个棋子,就是几个块。

代码如下

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <unistd.h>
#include <sched.h>
#include <ctype.h>

#define FIRST   1
#define SECOND  2

#define MAX_LENGTH 10

struct xyStruct
{
	int x;
	int y;
};
#if 1
int buf[MAX_LENGTH][MAX_LENGTH] = {{1,1,1,0,0,1,1,1,0,0},
								   {1,1,1,0,0,1,0,1,0,0},
								   {0,0,0,0,0,1,1,1,0,0},
								   {0,0,1,1,0,0,0,0,0,0},
								   {0,0,1,0,1,1,1,1,0,0},
								   {1,1,1,0,0,1,1,1,0,0},
								   {1,0,0,0,0,1,1,1,0,0},
								   {1,1,0,0,0,1,1,1,0,0},
								   {0,0,1,0,0,1,1,1,0,0},
								   {0,0,1,0,0,1,1,1,0,0}};

int flag[MAX_LENGTH][MAX_LENGTH] = {{FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
							 	    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST},
								    {FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST,FIRST}};
#endif
int locate[4][2] = {{ 1, 0},
				    {-1, 0},	
				    { 0, 1},
				    { 0,-1}};
struct xyStruct func(int x , int y)
{
	flag[x][y] = SECOND;
	struct xyStruct res;
	int tmpH = 0;
	int tmpZ = 0;
	int i = 0;
	if(buf[x][y] == 1)
	{
		for(i = 0 ; i < 4 ; i++)
		{
			tmpH = x + locate[i][0];
			tmpZ = y + locate[i][1];
			if(tmpH >= 0 && tmpH < MAX_LENGTH && tmpZ >= 0 && tmpZ < MAX_LENGTH)
			{
				if((buf[tmpH][tmpZ] == 1) && (flag[tmpH][tmpZ] == FIRST))
				{
					func(tmpH , tmpZ);
					//printf("tmpH = %d , tmpZ = %d\n" , tmpH , tmpZ);
					buf[tmpH][tmpZ] = 0; 
				}
				else
					flag[tmpH][tmpZ] = SECOND;
			}

		}	
	}
	if(x >= MAX_LENGTH - 1)
	{
		res.x = 0;
		res.y = y + 1;
	}
	else
	{
		res.x = x + 1;
		res.y = y;
	}
	return res;
}				    
int main()
{
	int xx = 0;
	int yy = 0;
	while(yy <= MAX_LENGTH - 1)
	{
		printf("xx = %d , yy= %d\n" , xx , yy);
		struct xyStruct xy = func(xx , yy);
		xx = xy.x;
		yy = xy.y;
	}
	int *p = &(buf[0][0]);
	printf("result : \n");
	for(int j = 0 ; j < MAX_LENGTH ; j++)
	{
		for(int i = 0 ; i < MAX_LENGTH ; i++)
		{
			printf("%d " , *p);
			p++;
		}
		printf("\n");
	}

	return 0;
}

结果如下:

最后再遍历一下,结果是5个。

其实还有广度搜索算法,我没看懂

猜你喜欢

转载自blog.csdn.net/wssjn1994/article/details/86480565