题解 | #坐标移动#

坐标移动

http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

思路:

使用状态机,如下图: 注意:图中的“其他”指的是全集减去该状态已画出的输入结合 比如:多余状态1来说,“其他”包括 W/A/S/D 以及无效输入;对状态3来说,“其他”表示除分号外的所有输入 ###alt

代码:


#include<iostream>
#include<bits/stdc++.h>

using namespace std;

int dir;
int pace=0;
int x=0,y=0;
int transState(int inState, char ch){
    if(inState==0){
        if(ch==';'){
            pace=0;
            return 0;
        }
        else if(ch=='A'||ch=='W'||ch=='S'||ch=='D'){
            dir=ch;
            return 1;
        }
        else return 3;
    }
    else if(inState==1){
        if(ch==';'){
            pace=0;
            return 0;
        }
        else if('0'<=ch&&ch<='9'){
            pace=ch-'0';
            return 2;
        }
        else return 3;
    }
    else if(inState==2){
        if(ch==';'){
            if(dir=='A'){
                x-=pace;
            }
            else if (dir=='D'){
                x+=pace;
            }
            else if (dir=='W'){
                y+=pace;
            }
            else if (dir=='S'){
                y-=pace;
            }
            pace=0;
            return 0;
        }
        else if('0'<=ch&&ch<='9'){
            pace*=10;
            pace+=ch-'0';
            return 2;
        }
        else return 3;
    }
    else if(inState==3){
        if(ch==';'){
            pace=0;
            return 0;
        }
        else return 3;
    }
    return 3;
}

int main(){
    string input;
    getline(cin, input);
    int len=input.size();
    int state=0;
    for(int i=0;i<len;i++){
        state = transState(state, input[i]);
    }
    cout<<x<<','<<y;
    return 0;
}
全部评论

相关推荐

人来疯的伊登等一个offer:轮抽象,还得看我这个,我甚至消息都没发😂查看图片
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务