Skip to content

Latest commit

 

History

History
107 lines (92 loc) · 2.17 KB

q006.md

File metadata and controls

107 lines (92 loc) · 2.17 KB

机器人坐标问题

问题描述

有一个机器人,给一串指令,L左转 R右转,F前进一步,B后退一步,问最后机器人的坐标,最开始,机器人位于 0 0,方向为正Y。 可以输入重复指令n : 比如 R2(LF) 这个等于指令 RLFLF。 问最后机器人的坐标是多少?

解题思路

这里的一个难点是解析重复指令。主要指令解析成功,计算坐标就简单了。

源码参考

func run(s string) (x, y int) {
	cmdList := resolveCmd(s)

	face := "Y"
	for _,c := range cmdList {
		if c == "L" {
			if face == "Y" {
				face = "-X"
			}else if face == "-Y"{
				face = "X"
			}else if face == "X" {
				face = "Y"
			}else {
				face = "-Y"
			}
		}else if c == "R" {
			if face == "Y" {
				face = "X"
			}else if face == "-Y"{
				face = "-X"
			}else if face == "X" {
				face = "-Y"
			}else {
				face = "Y"
			}
		}else if c == "F" {
			if face == "Y" {
				y += 1
			}else if face == "-Y" {
				y -= 1
			}else if face == "X" {
				x+=1
			}else {
				x-=1
			}
		}else if c == "B" {
			if face == "Y" {
				y-=1
			}else if face == "-Y" {
				y+=1
			}else if face == "X" {
				x+=1
			}else {
				x-=1
			}
		}
	}
	return
}

func resolveCmd(s string) ([]string){

	cmdList := make([]string,0)
	repeatCount := 0
	isStart := false
	tempCmd := ""

	for _,v := range s {
		ns := string(v)
		//如果是字符串,则标识下一步是重复步骤
		if ns >= "0" && ns <= "9" {
			t,_ := strconv.Atoi(ns);
			repeatCount = t
		}else if ns == "(" {
			isStart = true
		}else if ns == ")" {
			c := strings.Repeat(tempCmd,repeatCount)

			tempList := make([]string,strings.Count(c,""))

			for i,v1 := range c {
				tempList[i] = string(v1)
			}

			//当解析结束时,重复命令并保存到列表中
			cmdList = append(cmdList,tempList...)
			isStart = false
			repeatCount = 0
			tempCmd = ""
		}else if isStart{
			tempCmd += ns
		}else{
			cmdList = append(cmdList,ns)
		}
	}
	return cmdList
}

源码解析

这里用了最笨的方法,枚举方向和行动,逐字解析命令。示例中只实现了一次重复指令。更复杂的是多次重复指令。例如R2(B2(LF)BF2(BF))FBFR2(B2(LF2(RF)))F