最新消息:点击查看大S的省钱秘笈

格雷码(Gray Code) C语言 DFS版

编程相关 Slyar 148浏览 0评论

文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

Description

Gray code is an interesting code sequence and has many applications in computer science. No matter you have known it before or not, here are some introductions about its features:
(1) Gray code has 2^n unique elements;
(2) Each element contains n digits of 0 or 1;
(3) Each pair of adjacent elements has exactly one different digit.
For example, when n=2, one of the gray code sequence is: 00,01,11,10.
Now, the task is quite simple, given a positive integer n, generate the corresponding Gray code sequence.

Input

Input may contain multiple test cases. Each test case consists of one positive integer n(n<=16), Input is terminated by a case with n=0, which should not be processed.

Output

For each test case, output the corresponding Gray code sequence, one element per line. There may be multiple answers, any of them will be accepted. Please output a blank line after each test case.

Tips:注释很重要,很久以前的程序不加注释很容易看不懂...

输出N位前2^N个格雷码,因为每次只改变相邻的一个数,可以使用深度优先搜索,每次改变节点就好了。

转载请注明:Slyar Home » 格雷码(Gray Code) C语言 DFS版

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (5)

  1. 绝对赞赞赞!!!!帮了我好大的忙!
    Cathy2年前 (2015-05-08)回复
  2. 里面的递归太高深了
    霸气的雷公20124年前 (2013-04-04)回复
  3. 我对格雷码的特点不是很了解,确实看不懂里面的递归。。。
    L4年前 (2012-11-27)回复
  4. 謝謝你的程式碼,讓我對遞迴有更深的瞭解。
    monkey4135年前 (2012-03-29)回复
  5. 好,不过对格雷码的特点不是很了解的人,对里面的递归看不懂
    匿名8年前 (2009-03-13)回复