Leetcode
Hard
DFS
Link: https://leetcode.com/problems/robot-room-cleaner/description/
难点在于机器人是第一视角 所以我们需要手动从机器人的角度实现dfs(旋转 找下一个方向)
如果现在机器人的方向是朝北 我们希望机器人走到东边的一个格子 就需要先turnRight()
然后再move()
接着我们需要旋转180度再往前走回到原来的格子 下一个方向是朝南 因此我们需要先再转180度 让机器人朝东 接着循环刚才的动作先turnRight()
再move()
class Solution {
public void cleanRoom(Robot robot) {
Set<String> set = new HashSet<>();
set.add("0,0");
dfs(0, 0, 0, set, robot);
}
private void dfs(int x, int y, int curDir, Set<String> set, Robot robot){
robot.clean();
int[][] dirs = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
for(int i=1; i<=4; i++){
robot.turnRight();
int nextDir = (i+curDir)%4;
int nextx = x+dirs[nextDir][0];
int nexty = y+dirs[nextDir][1];
if(!set.contains(nextx+","+nexty) && robot.move()){
set.add(nextx+","+nexty);
dfs(nextx, nexty, (curDir+i)%4, set, robot);
robot.turnLeft();
robot.turnLeft();
robot.move();
robot.turnLeft();
robot.turnLeft();
}
}
}
}
Link: https://leetcode.com/problems/edit-distance/
Jan 8, 2024Code class Solution: def smallestRangeI(self, nums: List[int], k: int) -> int: nums.sort() if nums[-1]-nums[0]<=2*k: return 0 else: return nums[-1]-nums[0]-2*k
Dec 9, 2023Link: https://leetcode.com/problems/implement-magic-dictionary/
Dec 9, 2023Code class Solution: def minSteps(self, s: str, t: str) -> int: countS = collections.Counter(s) countT = collections.Counter(t) ans = 0 for char in countS.keys(): ans += max(0, countS[char]-countT[char]) return ans class Solution {
Dec 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up