是的,这段代码有一些错误。

首先,在for循环的条件应该是i < commands.size(),而不是i < commands。

其次,在if语句中,应该使用双等号(==)进行相等比较,而不是单等号(=)进行赋值。例如,if (x_dir == 0 && y_dir == 1)。

另外,在计算maxway时,应该使用pos_s * pos_s + pos_y * pos_y,而不是x_dir * x_dir + y_dir * y_dir。

最后,在循环中,应该先判断是否撞到障碍物,然后再执行pos_s += x_dir; pos_y += y_dir;,否则会先移动一步再判断是否撞到障碍物。

以下是修正后的代码:

class Solution { public: int robotSim(vector& commands, vector<vector>& obstacles) { int x_dir = 0, y_dir = 1, pos_s = 0, pos_y = 0; int maxway = 0; unordered_set<vector> hash_set{obstacles.begin(), obstacles.end()}; for (int i = 0; i < commands.size(); i++) { if (commands[i] < 0) { if (x_dir == 0 && y_dir == 1) { if (commands[i] == -1) { x_dir = 1; y_dir = 0; } if (commands[i] == -2) { x_dir = -1; y_dir = 0; } } if (x_dir == 1 && y_dir == 0) { if (commands[i] == -1) { x_dir = 0; y_dir = -1; } if (commands[i] == -2) { x_dir = 0; y_dir = 1; } } if (x_dir == 0 && y_dir == -1) { if (commands[i] == -1) { x_dir = -1; y_dir = 0; } if (commands[i] == -2) { x_dir = 1; y_dir = 0; } } if (x_dir == -1 && y_dir == 0) { if (commands[i] == -1) { x_dir = 0; y_dir = -1; } if (commands[i] == -2) { x_dir = 0; y_dir = 1; } } } else { while (commands[i] > 0) { int next_s = pos_s + x_dir; int next_y = pos_y + y_dir; if (hash_set.find({next_s, next_y}) != hash_set.end()) { break; } pos_s = next_s; pos_y = next_y; commands[i]--; } maxway = max(maxway, pos_s * pos_s + pos_y * pos_y); } } return maxway; } }


原文地址: https://www.cveoy.top/t/topic/icIv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录