Red Black Tree
Description
Red-black tree is a special kind of colored self-balancing binary tree.
A binary tree is considered red-black as long as the following conditions are satisfied: Rule 1. Each node is either red or black. Rule 2. The root node is black. Rule 3. All leaf nodes are black. (Special black NIL nodes are always used as leaf nodes, so this rule can be ignored in this problem.) Rule 4. Both children of every red node are black. (Every red node must have a black parent.) Rule 5. Every simple path from a node to a descendant leaf contains the same number of black nodes.
So the following binary tree is a red-black tree. Note: the small black square nodes are NIL nodes.
A tree can be represented as a matrix (however, a matrix may not only represent a tree). If the value of i-th row and j-th column of the matrix is 1, then it means an edge exists from node i to node j (node i is the parent of node j). Note: the NIL nodes are not included in matrix.
Given the color of each node, as well as the matrix, please determine whether they represent a red-black tree.
Input
This problem contains multiple test cases. Each test case starts with an integer N (1 <= N <= 100), indicating the number of nodes. Then N lines follow, each line contains a char indicating the color of the node, which can be either ‘B’ (black) or ‘R’ (red). Then a N*N matrix follows.
Output
For each test case, only one word should be outputted. ‘Yes’ – if it is a red-black tree, ‘No’ – if it is not.
Sample
Input
6
B
B
R
B
R
B
0 1 1 0 0 0
0 0 0 0 0 0
0 0 0 1 0 1
0 0 0 0 1 0
0 0 0 0 0 0
0 0 0 0 0 0
6
R
B
R
B
R
B
0 1 1 0 0 0
0 0 0 0 0 0
0 0 0 1 0 1
0 0 0 0 1 0
0 0 0 0 0 0
0 0 0 0 0 0
Output
Yes
No
Comments