您的位置:首页 > 其它

连通性问题

2018-03-28 16:02 120 查看
给定一个方阵,定义连通:上下左右相邻,并且值相同。
可以想象成一张地图,不同的区域被涂以不同颜色。
输入:
整数N, (N<50)表示矩阵的行列数
接下来N行,每行N个字符,代表方阵中的元素
接下来一个整数M,(M<1000)表示询问数
接下来M行,每行代表一个询问,
格式为4个整数,y1,x1,y2,x2,
表示(第y1行,第x1列) 与 (第y2行,第x2列) 是否连通。
连通输出true,否则false
例如:
10
0010000000
0011100000
0000111110
0001100010
1111010010
0000010010
0000010011
0111111000
0000010000
0000000000
3
0 0 9 9
0 2 6 8
4 4 4 6

程序应该输出:
false
true
true#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lian_tong(char* data[], int len, int y1, int x1, int y2, int x2)
{
if (y1 == y2 && x1 == x2)
return 1;
char old = data[y1][x1]; //old==0
data[y1][x1] = '*'; //做标记,走过就不再走了

//为啥写data[y1 - 1][x1] == old 深搜的回溯
//因为当碰见值为1时,说明碰见墙,不能往过去走了,的换一个方向
if (y1 > 0 && data[y1 - 1][x1] == old && lian_tong(data, len, y1 - 1, x1, y2, x2))
{
data[y1][x1] = old;
return 1;
}

if (y1<len - 1 && data[y1 + 1][x1] == old && lian_tong(data, len, y1 + 1, x1, y2, x2))
{
data[y1][x1] = old;
return 1;
}
if (x1>0 && data[y1][x1 - 1] == old && lian_tong(data, len, y1, x1 - 1, y2, x2)) {
data[y1][x1] = old;
return 1;
}
if (x1 < len - 1 && data[y1][x1 + 1] == old && lian_tong(data, len, y1, x1 + 1, y2, x2))
{
data[y1][x1] = old;
return 1;
}
data[y1][x1] = old;
return 0;
}

void main()
{

//切记路径 要跟main函数放一块
FILE *fp1 = fopen("1.txt", "r");

int len = 0;
char arr[10] = {0};
fgets(arr, 10, fp1);
len = atoi(arr);
printf("%d\n", len);
//定义char类型数组
char* *data = (char**)malloc(len*sizeof(char*));
for (int i = 0; i < len; i++)
{
data[i] = (char*)malloc(len + 2);
memset(data[i], 0, len + 2);
char *pp = data[i];
fgets(data[i], len + 2, fp1);
printf("%s", data[i]);
}
fclose(fp1);

int m = 0;
scanf("%d", &m);
for (int i = 0; i < 10; i++)
{
char arr[1024] = { 0 };

fflush(stdin);
gets(arr);
int shu[4] = { 0 };
int f1 = 0;
int tail = 0;
int f2 = 0;
int flag = 1;
while (flag >= 0)
{
if (arr[f1] != ' '&&arr[f1] != '\0')
{
tail++;
}
else
{
char mp[1024] = { 0 };
strncpy(mp, arr + f1 - tail, tail);
shu[f2] = atoi(mp);
f2++;
tail = 0;
}
f1++;
if (arr[f1] == '\0')
{
flag--;
}
}
int x = lian_tong(data, len, shu[0], shu[1], shu[2], shu[3]);
printf("%s\n", x ? "true" : "false"); //三目运算符
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: