技巧
递归
思路
基本汉诺塔问题 。注意数组边界换算处理
实现
package main import ( "os" "io" "bufio" . "fmt" ) var m map[string]int var g [][]string // 生成分割线 func getHr(lineCnt int) string{ line := "" for i := 0; i < lineCnt; i++{ line += "-" } return line } // 获取当前g的字符串 func gString() string{ str := "" for i :=0;i<len(g);i++ { for j :=0;j<len(g[i]);j++ { str += g[i][j] } if i + 1 != len(g) { str = Sprintf("%s\n",str) } } return str } // 将x柱上的圆盘移动到y柱 func gChange(x, y string){ xcol, ycol := m[x],m[y] width := 0 // 找到x最上面的圆盘 并且获取长度 for i:= 0; ;i++ { if g[i][xcol] =="*" { g[i][xcol] = "|" width++ for k :=1; g[i][xcol + k] == "*";k++{ g[i][xcol - k], g[i][xcol + k] = ".","." width += 2 } break } } for i:= 0; ;i++ { if len(g) == i + 1 || g[i+1][ycol] =="*" { g[i][ycol] = "*" width-- for k := 1; width != 0; k++{ g[i][ycol - k],g[i][ycol + k] = "*","*" width-=2 } break } } } func move(a, b, c ,hr string, n int){ if n == 1 { gChange(a, c) Println(hr) Println(gString()) return } move(a, c, b, hr,n-1) Println(hr) gChange(a, c) Println(gString()) move(b, a, c,hr,n-1) } // https://ac.nowcoder.com/acm/problem/201605 func NC201605(_r io.Reader, _w io.Writer){ in, out := bufio.NewReader(_r), bufio.NewWriter(_w) defer out.Flush() var n int Fscan(in, &n) //初始化图形 g = make([][]string, n + 2) m = make(map[string]int) m["b"] = (3*(2*n+1)+4) / 2 m["a"] = m["b"] - 1 - 2*n-1 m["c"] = m["b"] + 1 + 2*n+1 for i := 0; i < n + 2; i++{ g[i] = make([]string, 3 * (2 * n + 1) + 4) for j := 0; j < len(g[i]); j++ { g[i][j] = "." if i > 0 && (j == m["a"] || j == m["b"] || j ==m["c"]){ g[i][j] = "|" } if i > 1 && j >= m["a"] - n + n+1-i && j <= m["a"] + n - (n+1-i) { g[i][j] = "*" } } } Println(gString()) if n %2==0 { move("a","b","c",getHr(3*(2*n+1)+4),n) }else { move("a","c","b",getHr(3*(2*n+1)+4),n) } } func main(){ NC201605(os.Stdin, os.Stdout) }