首页 > 试题广场 >

坐标移动

[编程题]坐标移动
  • 热度指数:614071 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}我们定义一个无限大的二维网格上有一个小人,小人初始位置为 (0,0) 点,小人可以读取指令上下左右移动。一个合法的指令由三至四个符号组成:
\hspace{23pt}\bullet\,第一个符号为 \texttt{ 中的一个,代表小人移动的方向;分别代表向左、向右、向上、向下移动;记某个时刻小人的坐标为 (x,y),向左移动一格即抵达 (x-1,y)、向右移动一格即抵达 (x+1,y)、向上移动一格即抵达 (x,y+1)、向下移动一格即抵达 (x,y-1)
\hspace{23pt}\bullet\,最后一个符号为 \texttt{`;'},代表指令的结束,该符号固定存在;
\hspace{23pt}\bullet\,中间为一个大于 0 且小于 100 的数字,代表小人移动的距离。特别地,如果这个数字小于 10,那么它可能包含一个前导零,此时也视为合法。

\hspace{15pt}如果你遇到了一个不合法的指令,则直接忽略;例如,指令 \texttt{ 是不合法的,因为 100 超出了规定的数字范围;\texttt{ 也是不合法的,因为 \texttt{Y} 不是 \texttt{ 中的一个。
\hspace{15pt}输出小人最终的坐标。

输入描述:
\hspace{15pt}在一行上输入一个长度 1 \leqq {\rm length}(s) \leqq 10^4,由大写字母、数字和分号(\texttt{`;'})构成的字符串 s,代表输入的指令序列。保证字符串中至少存在一个 \texttt{`;'},且末尾一定为 \texttt{`;'}


输出描述:
\hspace{15pt}在一行上输出一个两个整数,代表小人最终位置的横纵坐标,使用逗号间隔。
示例1

输入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出

10,-10

说明

\hspace{15pt}对于这个样例,我们模拟小人的移动过程:
\hspace{23pt}\bullet\,第一个指令 \texttt{ 是合法的,向左移动 10 个单位,到达 (-10,0) 点;
\hspace{23pt}\bullet\,第二个指令 \texttt{ 是合法的,向下移动 20 个单位,到达 (-10,-20) 点;
\hspace{23pt}\bullet\,第三个指令 \texttt{ 是合法的,向上移动 10 个单位,到达 (-10,-10) 点;
\hspace{23pt}\bullet\,第四个指令 \texttt{ 是合法的,向右移动 30 个单位,到达 (20,-10) 点;
\hspace{23pt}\bullet\,第五个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第六个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第七个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第八个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第九个指令 \texttt{ 是合法的,向左移动 10 个单位,到达 (10,-10) 点。
示例2

输入

ABC;AKL;DA1;D001;W023;A100;S00;

输出

0,0

说明

\hspace{15pt}在这个样例中,全部指令均不合法,因此小人不移动。
示例3

输入

A00;S01;W2;

输出

0,1

备注:
本题已于下方时间节点更新,请注意题解时效性:
1. 2025-05-15 更新题面,新增几组hack数据(暂未进行重测)。
2. 2024-12-16 更新题面。
import sys

cmds = input().split(';')

def check(cmd: str):
    if len(cmd) <= 1:
        return False
    if not cmd.startswith(("A", "D", "W", "S")):
        return False
    if not cmd[1:].isdigit():
        return False
    if not int(cmd[1:]) < 100:
        return False
    return True

directions = {
    'A': [-1, 0],
    'D': [1, 0],
    'W': [0, 1],
    'S': [0, -1]
}

x, y = 0, 0
for cmd in cmds:
    # 检查指令的有效性
    if check(cmd):
        dis = int(cmd[1:])
        dx, dy = directions[cmd[0]]
        x += dx * dis
        y += dy * dis

print(f'{x},{y}')


发表于 2025-07-01 15:53:37 回复(0)
s = input().split(';')
x = 0
y = 0
for i in range(len(s)):
    if len(s[i])<2&nbs***bsp;len(s[i])>3:
        continue
    if s[i][0] == 'A'&nbs***bsp;'S'&nbs***bsp;'D'&nbs***bsp;'W':
        t = s[i][1:]
        if t.isdigit():
            num = int(t)
        else: continue
        if s[i][0]=='A':
            x = x - num
        elif s[i][0] == 'D':
            x = x + num
        elif s[i][0] == 'W':
            y = y + num
        elif s[i][0] == 'S':
            y = y - num
        else: continue
    else: continue
print(f"{x},{y}")
发表于 2025-06-14 15:39:29 回复(0)
l = input().split(";")
Dir = ["W","S","A","D"]
x = 0
y = 0
for i in l:
    if i != "" and i[0] in Dir:
        try:
            n = int(i[1:])
            if 2<=len(i)<=3 and 0<n<100:
                if i[0] == "W":
                    y += n
                if i[0] == "S":
                    y -= n
                if i[0] == "A":
                    x -= n
                if i[0] == "D":
                    x += n
        except:
            continue
print(str(x) + "," + str(y))

发表于 2025-06-08 20:01:03 回复(0)
好像numpy写坐标好用一点,但是这里边导入不了
import sys

x,y=0,0
def x_plus(x_p):
    global x
    x += x_p

def x_minus(x_m):
    global x
    x -= x_m

def y_plus(y_p):
    global y
    y += y_p

def y_minus(y_m):
    global y
    y -= y_m

direction = {'A':x_minus,'D':x_plus,'W':y_plus,'S':y_minus}

for line in sys.stdin:
    a = line.split()
    if a:
        cmd_list = a[0].split(';')
        for cmd in cmd_list:
            if 2<=len(cmd)<=3 and (cmd[0] in direction):
                try:
                    num = int(cmd[1:])
                    direction[cmd[0]](num)
                except:
                    continue
print(f'{x},{y}')

发表于 2025-05-26 15:14:02 回复(0)
position_x = 0
position_y = 0

movements = [movement for movement in input().split(";") if movement]

for movement in movements:
    direction = movement[0]
    distance = "".join(movement[1:])

    if not distance.isdigit():
        continue

    distance = int(distance)

    if distance > 99:
        continue

    if direction == "D":
        position_x += distance
    elif direction == "A":
        position_x -= distance
    elif direction == "W":
        position_y += distance
    elif direction == "S":
        position_y -= distance

print(f"{position_x},{position_y}")
发表于 2025-05-09 18:33:33 回复(0)
import sys

move_dic = {'A':[-1,0],'D':[1,0],'W':[0,1],'S':[0,-1]}

position = [0,0]
moves = input().split(';')

def one_move(position, move):
    if move == '':
        return position
    if move[0] not in {'A','D','W','S'}:
        return position
    if len(move[1::]) == 0:
        return position
    for string in move[1::]:
        if string not in {'1','2','3','4','5','6','7','8','9','0'}:
            return position
    distenc = [move_dic[move[0]][0]*int(move[1::]),move_dic[move[0]][1]*int(move[1::])]
    output = [distenc[0]+position[0],distenc[1]+position[1]]
    return output

for move in moves:
    position = one_move(position,move)

print(str(position[0])+','+str(position[1]))
发表于 2025-04-09 23:02:53 回复(0)
s = input().split(';')
a = ['A', 'D', 'W', 'S']
b = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
x = y = 0
def move(c, d, x, y):
    if c == 'A':
        x -= d
    elif c == 'D':
        x += d
    elif c == 'W':
        y += d
    elif c == 'S':
        y -= d
    return x, y
for i in s:
    if i != '' and i[0] in a:
        if len(i) == 2 and i[1] in b:
            x, y = move(i[0], int(i[1]), x, y)
        elif len(i) == 3 and i[1] in b and i[2] in b:
            x, y = move(i[0], int(i[1:3]), x, y)
    else:
        continue
print(x, end=',')
print(y)
发表于 2025-04-01 15:53:13 回复(0)
str1 = str(input())
str1_list = [i for i in str1.split(";") if len(i) != 0]
str1_list = [i for i in str1_list if i[0] in ["A", "D", "W", "S"]]
str2_list = []
for i in str1_list:
    try:
        if int(i[1:]) >= 1 and int(i[1:]) <= 99:
            str2_list.append(i)
    except:
        ''
a, b = 0, 0
for i in str2_list:
    fx, val_ = i[0], int(i[1:])
    if fx == "A":
        a -= val_
    if fx == "D":
        a += val_
    if fx == "W":
        b += val_
    if fx == "S":
        b -= val_
print('{},{}'.format(a,b))

发表于 2025-03-11 21:43:26 回复(0)
# 定义,二维网格上有一个小人,初始位置为(0,0),某时刻的位置为(x,y)
# 定义指令:"A/D/W/S" 代表向左、向右、向上、向下移动,“;”代表指令结束
# 非法指令跳过

X = "key1"
Y = "key2"
x = 0
y = 0

coord = {X:x,Y:y}
order = input().split(";")
# print(order)
for i in order:
   
    try:
        if 2 <= len(i) <= 3 and i[0] == "A":
            coord[X] -= int(i[1:])
             # 向左X-
        elif 2 <= len(i) <= 3 and i[0] == "S":
            coord[Y] -= int(i[1:])
             # 向下Y-
        elif 2 <= len(i) <= 3 and i[0] == "W":
            coord[Y] += int(i[1:])
             # 向上Y+
        elif 2 <= len(i) <= 3 and i[0] == "D":
            coord[X] += int(i[1:])
             # 向右X+
        else:
            continue
        # print(coord)
    except ValueError:
        continue
x = coord[X]
y = coord[Y]
print("{X},{Y}".format(X=x,Y=y))

发表于 2025-03-08 01:50:56 回复(0)
a = input().split(";")
lis = ["W","A","S","D"]
jihe = []
my_dict = {
    "W" : 0,
    "S" : 0,
    "A" : 0,
    "D" : 0
 }
for i in lis :
    for k in range(1,100):
        b = ""
        b = str(i) + str(k)
        jihe.append(b)
for j in a:
    if j in jihe:
        c = j[1:]
        d = j[0]
        my_dict[d] += int(c)
n,m = 0,0
n += my_dict["D"]
n -= my_dict["A"]
m += my_dict["W"]
m -= my_dict["S"]
print(str(n)+","+str(m))

发表于 2025-03-06 14:05:37 回复(0)
x = 0
y = 0
a = input().split(';')

for i in a:
    if 1 < len(i) < 4:  # 确保指令长度在2到3之间
        if i[0] in ['A', 'D', 'W', 'S']:
            try:
                step = int(i[1:])  # 将指令的步数部分转化为整数
                if 0 < step < 100:  # 确保步数在1到99之间
                    if i[0] == 'A':
                        x -= step
                    elif i[0] == 'D':
                        x += step
                    elif i[0] == 'W':
                        y += step
                    elif i[0] == 'S':
                        y -= step
            except:
                # 如果步数部分不能转化为整数,则跳过此指令
                continue

print(f'{x},{y}')
发表于 2025-03-06 13:38:34 回复(0)
import re
s = input().strip().split(';')
x = 0
y = 0
for order in s:
    if order:
        boolean = re.match('^[AWSD][1-9][0-9]?$',order)

        if boolean:

            if order[:1].lower() == 'a':
                x = x-int(order[1:])  
            elif order[:1].lower() == 'd':
                x = x+int(order[1:])
            elif order[:1].lower() == 'w':
                y = y+int(order[1:])
            else:
                y = y-int(order[1:])
print(str(x)+','+str(y))
发表于 2025-02-28 21:14:11 回复(0)
instruct = input().split(';')
position = [0, 0]
for ins in instruct:
    l = ins[0:1]
    r = ins[1:]
    try:
        steps = eval(r)
    except:
        continue
    if l == 'A':
        position[0] -= steps
    elif l == 'S':
        position[1] -= steps
    elif l == 'D':
        position[0] += steps
    elif l == 'W':
        position[1] += steps
print(position[0],end=',')
print(position[1])

发表于 2025-02-19 13:02:56 回复(0)
class GridMover:
    def __init__(self):
        self.x = 0
        self.y = 0

    def move(self, direction, distance):
        if direction == 'A':
            self.x -= distance
        elif direction == 'D':
            self.x += distance
        elif direction == 'W':
            self.y += distance
        elif direction == 'S':
            self.y -= distance

    def process_commands(self, commands):
        commands_list = commands.split(';')
        for command in commands_list:
            if len(command) >= 2 and command[0] in 'ADWS' and command[1:].isdigit():
                distance = int(command[1:])
                if 1 <= distance <= 99:
                    self.move(command[0], distance)
        return f'{self.x},{self.y}'

input_commands = input()
mover = GridMover()
result = mover.process_commands(input_commands)
print(result)

发表于 2024-12-24 17:25:58 回复(1)
strrs = input().split(';')
def Check(strr):
    strr = [i for i in strr]
    int_list = [0,1,2,3,4,5,6,7,8,9]
    int_list = [str(i) for i in int_list]
    if (len(strr) == 0) or (len(strr) == 1) :
        return False
    if strr[0] in ['A','D','W','S']:
        for i in strr[1:]:
            if (i not in int_list):
                return False
    else:
        return False
    return True

def Cal(strrs_new):
    x = 0
    y = 0
    for strr_new in strrs_new:
        if strr_new[0] == 'A':
            x -= int(strr_new[1:])
        if strr_new[0] == 'D':
            x += int(strr_new[1:])
        if strr_new[0] == 'W':
            y += int(strr_new[1:])
        if strr_new[0] == 'S':
            y -= int(strr_new[1:])    
    return f'{x},{y}'
strrs_new = []
for i in strrs:
    a = Check(i)
    if a == True:
        strrs_new.append(i)
print(Cal(strrs_new))
发表于 2024-11-24 22:09:52 回复(0)
cord_list = input().split(';')
x, y = 0, 0
for cord in cord_list:
    if 2 <= len(cord) <= 3 and cord[1:].isdigit():
        d, step = cord[0], int(cord[1:])
        if d == 'A':
            x -= step
        elif d == 'D':
            x += step
        elif d == 'W':
            y += step
        elif d == 'S':
            y -= step

print(f'{x},{y}')

发表于 2024-11-07 17:01:08 回复(1)
看到这道题想起来以前用过的match case语句,试了不能运行,百度知道这是3.10才支持的语法,虽然没法用,但是给大家看个乐子
act=input().split(';')
start=[0,0]
for i in act:
    if not 2<=len(i)<=3:
        continue
    try:
        move=i[0]
        step=int(i[1:])
        match (move):
            case "W":
                start[1]+=step
            case "S":
                start[1]-=step
            case "A":
                start[0]-=step
            case "D":
                start[0]+=step
    except:
        continue
print(str(start[0])+','+str(start[1]))


发表于 2024-10-12 22:00:45 回复(0)
s = input().split(';')
x,y = 0,0
for move in s:
    if len(move) >= 2 and (move[1:]).isdigit():
        if move[0] == 'A' :
            x -= int(move[1:])
        elif move[0] == 'D' :
            x += int(move[1:])
        elif move[0] == 'W' :
            y += int(move[1:])
        elif move[0] == 'S' :
            y -= int(move[1:])
print(f'{x},{y}')

发表于 2024-10-07 18:28:36 回复(0)