LeetCode-874. Walking Robot Simulation(模拟行走机器人)

模拟行走机器人

LeetCode-874. Walking Robot Simulation(模拟行走机器人)_第1张图片

Walking Robot Simulation

LeetCode-874. Walking Robot Simulation(模拟行走机器人)_第2张图片

C语言没有set,做起来可能有点麻烦
这里用到了二分查找,应该算不上贪心算法,就是简单的走一遍


int comp(const void *a, const void *b)
{
     
    return (*(int **)a)[0] - (*(int **)b)[0];
}

bool isStop(int x, int y, int **ob, int obs)//二分查找
{
     
    int left = 0, right = obs, mid = obs / 2;
    int a = x + y * 30000;

    if (!obs || a > ob[right - 1][0] || a < ob[0][0]){
     
        return true;
    }
    if (a == ob[mid][0]){
     
        return false;
    }

    while (left + 1 < right){
     
        if(a > ob[mid][0]) {
     
            left = mid;
            mid = (left + right) / 2;
        } else if (a < ob[mid][0]){
     
            right = mid;
            mid = (left + right) / 2;
        } else {
     
            return false;
        }
    }

    return true;
}

int turn(int a, int cmd)
{
     
    int b = a;

    switch(a) {
     
    case 0:
        if(cmd == -1) b = 1; else b = 3; break;
    case 1:
        if(cmd == -1) b = 2; else b = 0; break;
    case 2:
        if(cmd == -1) b = 3; else b = 1; break;
    case 3:
        if(cmd == -1) b = 0; else b = 2; break;
    default:
        break;
    }
    
    return b;
}

int robotSim(int* commands, int commandsSize, int** obstacles, int obstaclesSize, int* obstaclesColSize)
{
     
    int x = 0, y = 0, re = 0, i;
    int flag = 0;
    int t[4][2] = {
     {
     0, 1}, {
     1, 0}, {
     0, -1}, {
     -1, 0}};

    for (i = 0; i < obstaclesSize; i++){
     
        obstacles[i][0] = obstacles[i][0] + obstacles[i][1] * 30000;
        //因为30000是obstacles的范围,障碍的纵坐标改变,新值以30000为单位变化,
        //因此,只要新值相等,原坐标必相同。
    }

    qsort(obstacles, obstaclesSize, sizeof(int *), comp);

    for (i = 0; i < commandsSize; i++){
     
        switch(commands[i]){
     
            case -1:
            case -2:
                flag = turn(flag, commands[i]);
                break;
            default:
                while(commands[i]--){
     
                    if(isStop(x+t[flag][0],y+t[flag][1],obstacles,obstaclesSize)){
     
                        x += t[flag][0];
                        y += t[flag][1];
                    }else{
     
                        break;
                    }
                }
                break;
        }

        re = re < x * x + y * y ? x * x + y * y : re;
    }

    //*obstaclesColSize = 2;

    return re;
}

结果
在这里插入图片描述
有点惨,等着有思路再优化吧…

你可能感兴趣的:(LeetCode)