Find Cycle

Find Cycle

A graph is a type of data structure that consists of nodes and edges that connect the nodes. An edge has a start node and end node, and we will only consider directed edges.

The figure below is an example of a graph with 8 nodes (labeled ‘1‘ through ‘8‘) and 9 edges. A path in a graph is a sequence of nodes that are connected by edges.

‘6->3->2->1‘ is an example of path in the graph below.



A "Cycle" is a special case of path; it has at least 2 nodes, and the start node and the end node of the path are the same.

For example, ‘1->5->2->1‘,‘7->8->7‘,‘5->2->1->5‘, and ‘8->7->8‘ are examples of cycle you can find in the graph above.



Given a graph, write a program that finds a cycle of the given graph.

If there‘s a cycle, write node numbers in ascending order, and write ‘0‘. If there is more than one cycle, choose and print out one cycle.

[Constraints]

N, the number of nodes satisfies 5<=N<=100, and M, the number of edges satisfies 1<=M<=1000.



[Input]

Several test cases can be included in the inputs. T, the number of cases is given in the first row of the inputs.

After that, the test cases as many as T (T <= 10) are given. The first line of each test case has N, the number of nodes, and M, the number of edges. The second line has M pairs of start node and end node. The nodes are labeled
form ‘1‘ to ‘N‘.

No edge has the same start and end node. All integers in the input are separated by a space.

We call the number of edges that come out of a node "degree".

For test cases #1-#3, the degree of all nodes is 1; for test cases #4-#6, the degree is 2 or less; for test cases #7-#10, there‘s no limit in degree.

Here, "degree of the node is 1" means that all nodes simply have only one edge coming out of the node.

(In the left graph above, from node 2, you can go to either node 1 or node 4 so the degree is not 1. In the right graph, on the contrary, the degree is 1.)

[Output]

Print answers for each of 10 test cases in 10 lines. Start each line with ‘#x‘ where x is the test case number, leave a space and print your answer.

When a cycle exists, enumerate numbers of the nodes in the cycle in ascending order. For example, the cycle ‘1->5->2->1‘ is written as ‘1 2 5‘.

If there is no cycle, just write ‘0‘.

[Sample Input/Output]

Input (Input consists of several lines, but the example below shows input for only 4 test cases represented through 9 lines to help you understand the format.)

4 -->T: the number of test cases

5 5 -->case 1

4 3 2 4 3 5 3 2 1 4

5 5 -->case 2

4 3 2 4 3 5 2 3 1 4

6 5 -->case 3

1 5 6 4 3 1 5 3 4 6

8 9 -->case 4

5 2 3 2 6 3 8 7 2 1 6 4 2 4 1 5 7 8

Output (Output is made up of 10 lines, but the example below shows output for only 4 test cases to help you understand the format.)

Case #1

2 3 4

Case #2

0

Case #3

1 3 5

Case #4

7 8

Note, for "Case 4" we can also output "1 2 5".

题目的意思比较简单,大意是从给出的线路中找出一个回环,然后将回环结果由小到大输出即可。

解题思路:首先构造一个N*N的矩阵,并初始化为全0,通过输入将有线路的矩阵标记为1,然后用深度递归的方法找到回环;在寻找的过程中需要维护两张表,Table表按顺序保存已经遍历过的非0节点,Hash表保存Table表中非0节点出现的顺序,也就是遍历的顺序。


Table[i]


1


2


3


4


5


6


7


8


Value


1


3


4


2


6


0


0


0


Hash[i]


1


2


3


4


5


6


7


8


Value


1


4


2


3


6


0


0


0

/*

You should use the statndard input/output

in order to receive a score properly.

Do not use file input and output

Please be very careful.

*/

#include <stdio.h>

#define MAX_M  1001

#define MAX_N  101

int Array[MAX_N][MAX_N];//
构造一个N*N的矩阵,用来保存输入的边数

int N,M;

int Answer;

int num = 0 ;

int Table[MAX_N];

int Hash[MAX_N];

int top ;//遍历过的非0点个数

int start ;//标志位

int temp;

//递归算法

int Cacluate(int node)

{

int i;

//int ret;

if (start !=-1)

return 0;

if (Hash[node] != 0)

{

//Table : 100 200 800 0 2 5 7 9 6 4 5

//Hash  : 1 0 1 0 7

//loop;

start = Hash[node];

//top--;

return 0;

}

//retr

top++;

Table[top] = node;

Hash[node] = top;

//if(Hash[node] == 1)

//      return node;

//Hash[node] = 1;

for(i=1;i<=N;i++)

{

if(Array[node][i] != 0  && node !=i)

{

Cacluate(i);

/*ret = Cacluate(i);

if(ret != 0)

{

return ret;

}*/

if (start !=-1)

return 0;

}

}

Hash[node] = 0;

top--;

return 0;

}

int main(void)

{

int T, test_case;

/*

The freopen function below opens input.txt file in read only mode, and afterward,

the program will read from input.txt file instead of standard(keyboard) input.

To test your program, you may save input data in input.txt file,

and use freopen function to read from the file when using scanf function.

You may remove the comment symbols(//) in the below statement and use it.

But before submission, you must remove the freopen function or rewrite comment symbols(//).

*/

freopen("input.txt", "r", stdin);

/*

If you remove the statement below, your program‘s output may not be rocorded

when your program is terminated after the time limit.

For safety, please use setbuf(stdout, NULL); statement.

*/

setbuf(stdout, NULL);

scanf("%d", &T);

for(test_case = 0; test_case < T; test_case++)

{

int i,j;

int t1,t2;

int loop = 0 ;

top = 0;

start = -1;

scanf("%d",&N);

scanf("%d",&M);

//初始化Array数组,全部初始化为0

for(i=1;i<=N;i++)

{

for(j=1;j<=N;j++)

{

Array[i][j] = 0 ;

}

}

//保存输入的边数,将有线路的边置为1

for(i=0;i<M;i++)

{

scanf("%d %d" , &t1,&t2);

//保存t1->t2的边之前先判断是否有t2->t1的边,如果有,直接按照大小顺序输出t1、t2,

if (Array[t2][t1]!=0)

{

if(t1<=t2)

printf("Case #%d\n%d %d\n",test_case+1,t1,t2);

else

printf("Case #%d\n%d %d\n",test_case+1,t2,t1);

loop = 1;

}

Array[t1][t2] = 1 ;     //将有线路的边置为1

}

if (loop!=0)

{

continue;//结束本次case循环,之后的代码不执行,进入下一个case。

}

for(i=0;i<=N;i++)//初始化两张表

{

Table[i] = 0;

Hash[i] = 0;

}

//start = -1;

for(i=1;i<=N;i++)

{

for(j=1;j<=N;j++)

{

if (Array[i][j] != 0)//如果不为0则循环遍历数据表

{

Cacluate(i);

if (start !=-1)

break;//跳出第一重for循环

}

}

if (start !=-1)

break;// 跳出第二重for循环,即结束遍历

}

printf("Case #%d\n", test_case+1);

//将得到的结果进行排序

if(start !=-1){

for(i=start;i<=top;i++)

{

for( j = start;j < top +start- i;j++)

{

if(Table[j] > Table[j+1])

{

temp = Table[j] ;

Table[j] = Table[j+1] ;

Table[j+1] = temp ;

}

}

}

//输出结果

for(i=start;i<top;i++)

{

printf("%d ",Table[i]);

}

printf("%d",Table[top]);

}

else  if(start ==-1)

printf("%d",Table[0]);

printf("\n");

/////////////////////////////////////////////////////////////////////////////////////////////

/*

Implement your algorithm here.

The answer to the case will be stored in variable Answer.

*/

/////////////////////////////////////////////////////////////////////////////////////////////

//Answer = 0;

// Print the answer to standard output(screen).

//

//printf("%d\n", Answer);

}

return 0;//Your program should return 0 on normal termination.

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-29 19:07:17

Find Cycle的相关文章

[leedcode 142] Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!).  我们已经得到了结论a=c,那么让两个指针分别从X

jQuery图片切换插件jquery.cycle.js

Cycle是一个很棒的jQuery图片切换插件,提供了很好的功能来帮助大家更简单的使用插件的幻灯功能 下载cycle插件并引入,此时,注意把引入它的代码放在引入jQuery主文件之后. <head> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src

Gartner&#39;s Hype Cycle for Emerging Technologies

2012 2013 2014 2015 2016 Gartner's Hype Cycle for Emerging Technologies

[LeetCode]Linked List Cycle

题目:Linked List Cycle 判断一个单链表中是否有环,要求常量空间复杂度: 思路: 使用两个指针同时从链表表头开始移动,一个移动一步,一个移动两步,直到两个指针重合或某一指针指向链尾. 两个指针重合则单链表有环存在,否则没有. 第二个指针以第一个指针的两倍的速度移动,而第一个指针每次移动一步,这样只要有环,两个指针必定能重合. bool LeetCode::hasCycle(ListNode *head){ if (!head)return false; ListNode *p =

Cycle Sort

Cycle sort的思想与计数排序太像了,理解了基数排序再看这个会有很大的帮助, 圈排序与计数排序的区别在于圈排序只给那些需要计数的数字计数,先看完文章吧,看完再回来理解这一句话 所谓的圈的定义,我只能想到用例子来说明,实在不好描述 待排数组[ 6 2 4 1 5 9 ] 排完序后[ 1 2 4 5 6 9 ] 数组索引[ 0 1 2 3 4 5 ] 第一部分 第一步,我们现在来观察待排数组和排完后的结果,以及待排数组的索引,可以发现 排完序后的6应该出现在索引4的位置上,而它现在却在位置0上

L - Points on Cycle

Description There is a cycle with its center on the origin. Now give you a point on the cycle, you are to find out the other two points on it, to maximize the sum of the distance between each other you may assume that the radius of the cycle will not

[Cycle.js] Hello World in Cycle.js

Now you should have a good idea what Cycle.run does, and what the DOM Driver is. In this lesson, we will not build a toy version of Cycle.js anymore. Instead, we will learn how to use Cycle.js to solve problems. We will start by making a simple Hello

[Cycle.js] Making our toy DOM Driver more flexible

Our previous toy DOM Driver is still primitive. We are only able to sends strings as the textContent of the container element. We cannot yet create headers and inputs and all sorts of fancy DOM elements. In this lesson we will see how to send objects

LeetCode(141): Linked List Cycle

Linked List Cycle: Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? 题意:判断一个链表中是否存在环. 思路:(参考别人的做法)采用"快慢指针"检查链表是否含有环.即让一个指针一次走一步,另一个指针一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇. 代码: public boolean h

The App Life Cycle &amp; The Main Function

The App Life Cycle Apps are a sophisticated interplay between your custom code and the system frameworks. The system frameworks provide the basic infrastructure that all apps need to run, and you provide the code required to customize that infrastruc