当前位置: 面试刷题>> 房屋染色 (经典算法题500道)


题目描述补充

房屋染色问题: 在一个小镇上,有N栋房屋排成一行,每栋房屋可以被染成红色、蓝色或绿色中的一种颜色。镇上的居民有一些特殊要求,他们不希望相邻的房屋颜色相同,因为这样的视觉效果不佳。同时,镇上的某些房屋已经被预先染上了颜色(这些颜色不可更改),而其他房屋则尚未上色。你的任务是编写一个算法,判断是否存在一种方案,能够按照居民的要求完成所有房屋的染色,同时满足相邻房屋颜色不同的条件。

输入

  • 一个整数N,表示房屋的数量。
  • 一个长度为N的字符串,其中每个字符表示对应房屋的初始颜色('R'表示红色,'B'表示蓝色,'G'表示绿色,'-'表示未上色)。

输出

  • 如果存在满足条件的染色方案,则输出"YES",否则输出"NO"。

示例

输入

4
RB-G

输出

YES

解释:第一栋房屋是红色,第二栋是蓝色,第四栋是绿色,第三栋房屋可以染成绿色或蓝色,以满足相邻房屋颜色不同的条件。

PHP 示例代码

function canPaintHouses($N, $houses) {
    $colors = ['R', 'B', 'G'];
    $memo = array_fill(0, 1 << $N, array_fill(0, 3, -1)); // 使用位运算和数组记录状态

    return dfs($houses, 0, 0, $memo) != -1;

    function dfs($houses, $index, $mask, &$memo) {
        if ($index == strlen($houses)) {
            return 1; // 所有房屋都已染色且满足条件
        }

        if ($memo[$mask][$houses[$index] != '-'] != -1) {
            return $memo[$mask][$houses[$index] != '-'];
        }

        $result = -1;
        for ($i = 0; $i < 3; $i++) {
            if (($houses[$index] == '-' || $houses[$index] == $colors[$i]) && 
                (($index == 0 || (($mask & (1 << ($index - 1))) == 0)) || // 确保与前一栋房屋颜色不同
                ($colors[$i] != $colors[ord($houses[$index - 1]) - ord('A')]))) {
                $nextMask = $mask | (1 << $index); // 更新当前房屋已染色的状态
                $nextResult = dfs($houses, $index + 1, $nextMask, $memo);
                if ($nextResult != -1) {
                    $result = $nextResult;
                    break;
                }
            }
        }

        $memo[$mask][$houses[$index] != '-'] = $result;
        return $result;
    }
}

$N = 4;
$houses = "RB-G";
echo canPaintHouses($N, $houses) ? "YES" : "NO";

Python 示例代码

Python 版本略有不同,因为它更直接地处理字符串和递归:

def canPaintHouses(N, houses):
    def dfs(index, prev_color):
        if index == N:
            return True
        if houses[index] != '-':
            return houses[index] != prev_color and dfs(index + 1, houses[index])
        for color in 'RGB':
            if color != prev_color:
                if dfs(index + 1, color):
                    return True
        return False

    return dfs(0, '')

N = 4
houses = "RB-G"
print("YES" if canPaintHouses(N, houses) else "NO")

JavaScript 示例代码

function canPaintHouses(N, houses) {
    function dfs(index, prevColor) {
        if (index === N) return true;
        if (houses[index] !== '-') {
            return houses[index] !== prevColor && dfs(index + 1, houses[index]);
        }
        for (let color of ['R', 'B', 'G']) {
            if (color !== prevColor) {
                if (dfs(index + 1, color)) return true;
            }
        }
        return false;
    }

    return dfs(0, '');
}

const N = 4;
const houses = "RB-G";
console.log(canPaintHouses(N, houses) ? "YES" : "NO");

码小课:在码小课网站上,你可以找到更多关于算法和数据结构的精彩内容,帮助你深入理解并掌握各种编程技巧,提升你的编程能力。

推荐面试题