首页 > 试题广场 >

坐标移动

[编程题]坐标移动
  • 热度指数:606804 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}我们定义一个无限大的二维网格上有一个小人,小人初始位置为 (0,0) 点,小人可以读取指令上下左右移动。

\hspace{15pt}一个合法的指令由三至四个符号组成:
\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\,中间为一个 \texttt{1-99} 的数字,代表小人移动的距离。
\hspace{15pt}如果你遇到了一个不合法的指令,则直接忽略;例如,指令 \texttt{ 是不合法的,因为 \texttt{100} 超出了 \texttt{1-99} 的范围;\texttt{ 也是不合法的,因为 \texttt{Y} 不是 \texttt{ 中的一个。

\hspace{15pt}输出小人最终的坐标。

输入描述:
\hspace{15pt}在一行上输入一个长度 1 \leqq {\rm length}(s) \leqq 10^4 ,仅由可见字符构成的字符串 s ,代表输入的指令序列。


输出描述:
\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;

输出

0,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)
a = input().split(";")
# print(a)
b = [i for i in a if len(i) >= 2]
o = [0,0]
for r in b:
    if "W" == r[0]:
        try:
            o = [o[0],o[1]+int(r[1:])]
        except:
            pass
    if "S" == r[0]:
        try:
            o = [o[0],o[1]-int(r[1:])]
        except:
            pass
    if "A" == r[0]:
        try:
            o = [o[0]-int(r[1:]),o[1]]
        except:
            pass
    if "D" == r[0]:
        try:
            o = [o[0]+int(r[1:]),o[1]]
        except:
            pass
    # print(o)

print(",".join(map(str,o)))
发表于 2024-09-30 05:13:26 回复(0)
def move(disp):
    dx, dy = 0, 0
    if is_disp(disp):
        if disp[0] == 'A':
            dx = -1*int(disp[1:])
        if disp[0] == 'D':
            dx = 1*int(disp[1:])
        if disp[0] == 'W':
            dy = 1*int(disp[1:])
        if disp[0] == 'S':
            dy = -1*int(disp[1:])
    return dx, dy

def is_disp(disp):
    if len(disp)>=2 and disp[0] in ('A','S','D','W') and disp[1:].isdigit():
        return True
    else:
        return False

if __name__ == "__main__":
    disps = input().strip().split(';')
    x, y = 0, 0
    for disp in disps:
        dx, dy = move(disp)
        x += dx
        y += dy
    print(f"{x},{y}")
发表于 2024-09-20 08:55:14 回复(0)
from ast import Pass
while True:
    try:
        s = input().split(';')
        x, y = 0, 0
        for move in s:
            if move == '':
                continue
            elif move[0] == 'A' and move[1:].isdigit():
                x -= int(move[1:])
            elif move[0] == 'W' and move[1:].isdigit():
                y += int(move[1:])
            elif move[0] == 'S' and move[1:].isdigit():
                y -= int(move[1:])
            elif move[0] == 'D' and move[1:].isdigit():
                x += int(move[1:])
        print(f'{x},{y}')
    except:
        break

发表于 2024-08-11 19:52:49 回复(1)
屎山代码
import string
#读取并分割
L=input().split(";")
#初始化坐标
x=0
y=0
#循环
for i in range(len(L)):
    #筛除长度大于3的无效数据
    if (len(L[i])>3):
        continue
    #判断后两位是否为数字,如不是,则舍弃
    try:
        n=int(L[i][1:3])
    except:
        continue
    #判断移动方向并写入坐标
    if (L[i][0]=="A"):
            x-=n
    elif (L[i][0]=="D"):
            x+=n
    elif (L[i][0]=="S"):
            y-=n
    elif (L[i][0]=="W"):
            y+=n
#打印坐标
print(x,end=",")
print(y)
发表于 2024-07-24 19:55:22 回复(0)
import re

input_list = input()

zhengze = r'\b[ADWS]\d{1,2}\b'
matches = re.findall(zhengze,input_list)

x = 0
y = 0

for match in matches:
    direction = match[0]
    distinct = int(match[1:])
       
    if direction == "A":
            x -= distinct
    if direction == "D":
            x += distinct
    if direction == "W":
            y += distinct
    if direction == "S":
            y -= distinct
       

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

发表于 2024-07-13 10:30:18 回复(0)