打印从(x,y)到(0,0)的所有路径

 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>

void route(int x , int y , char *path)
{
	if (x == 0 && y == 0)
	{
		strcat(path , "(0,0)");
		//打印路径
		puts(path);
		//把(0,0)从路径中删除
		int length = strlen(path);
		path[length - 5] = 0;//(0,0)的长度是5
		return;
	}
	if (x == 0)
	{
		/*strcat(path , "(0,");
		char c[2] = { 0 };
		c[0] = y + '0';
		strcat(path , c);
		strcat(path , ")->");*/
		sprintf(path , "%s(%d,%d)->" , path , x , y);//上面这段代码可以用sprintf实现

		route(x , y - 1 , path);
		//把(0,y)->从路径中删除
		int length = strlen(path);
		path[length - 7] = 0;
	}
	else if (y == 0)
	{
		strcat(path , "(");
		char c[2] = { 0 };
		c[0] = x + '0';
		strcat(path , c);
		strcat(path , ",0)->");
		route(x - 1 , y , path);
		//把(x,0)->从路径中删除
		int length = strlen(path);
		path[length - 7] = 0;
	}
	else
	{
		char c1[2] = { 0 };
		char c2[2] = { 0 };
		c1[0] = x + '0';
		c2[0] = y + '0';
		strcat(path , "(");
		strcat(path , c1);
		strcat(path , ",");
		strcat(path , c2);
		strcat(path , ")->");
		route(x - 1 , y , path);
		route(x , y - 1 , path);
		//把(x,y)->从路径中删除
		int length = strlen(path);
		path[length - 7] = 0;
	}
}

int main()
{
	char path[1000] = { 0 };
	int x , y;
	scanf("%d%d" , &x , &y);
	route(x , y , path);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43496435/article/details/113802427