【Lintcode】1514. Robot Room Cleaner

题目地址:

https://www.lintcode.com/problem/robot-room-cleaner/description

有个机器人,在一个房间里打扫卫生,房间可以看成一个矩形网格。机器人提供的API如下:

interface Robot {
	// 如果下一个格子开放并机器人可以进入返回true。
  	// 如果下一个格子阻塞并且机器人处于合适的格子中返回false。
  	boolean move();

  	// 在向左或向右转后,机器人还会待在原来的格子中。
  	// 每次转向是90度。
  	void turnLeft();
  	void turnRight();

  	// 清理合适的格子。
  	void clean();
}

( 0 , 0 ) (0,0) (0,0)出发,要求将所有”合适“的格子全清理一遍(题目保证合适的格子是连通的,并且出发位置是合适的)。

直接DFS。代码如下:

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public void cleanRoom(Robot robot) {
        // write tour code here
        int[] d = {1, 0, -1, 0, 1};
        dfs(0, 0, d, 0, new HashSet<>(), robot);
    }
    
    private void dfs(int x, int y, int[] d, int curD, Set<String> visited, Robot robot) {
    	// 把位置序列化成字符串,方便判重
        String loc = x + " " + y;
        if (visited.contains(loc)) {
            return;
        }
        
        visited.add(loc);
        robot.clean();
        for (int i = 0; i < 4; i++) {
        	// 如果能向前走,则走一步
            if (robot.move()) {
                dfs(x + d[curD], y + d[curD + 1], d, curD, visited, robot);
                goBack(robot);
            }
            
            robot.turnRight();
            curD = (curD + 1) % 4;
        }
    }
    
    private void goBack(Robot robot) {
    	// 转一百八十度
        robot.turnRight();
        robot.turnRight();
        // 向前走一格
        robot.move();
        // 把方向再恢复原状
        robot.turnLeft();
        robot.turnLeft();
    }
}

interface Robot {
    // Returns true if the cell in front is open and robot moves into the cell.
    // Returns false if the cell in front is blocked and robot stays in the current cell.
    boolean move();
    
    // Robot will stay in the same cell after calling turnLeft/turnRight.
    // Each turn will be 90 degrees.
    void turnLeft();
    void turnRight();
    
    // Clean the current cell.
    void clean();
}

时空复杂度 O ( n ) O(n) O(n) n n n是房间大小。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值