question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
binary-tree-coloring-game
Python solution with simple steps
python-solution-with-simple-steps-by-val-m6p7
Everything we need to know to answer if we can win this game the total tree size and left and right subtrees size, because we only have 3 options to choose t
valerab
NORMAL
2021-02-01T00:19:21.014030+00:00
2021-02-01T00:19:21.014072+00:00
94
false
Everything we need to know to answer if we can win this game the total tree size and left and right subtrees size, because we only have 3 options to choose to win this game:\n\n1. The choice left sub tree or red node, if left subtree more that whole tree \n1. The choice right sub tree or red node, if right subtree more that whole tree.\n1. The choice the parent node of red node, if red is not root and red subtree include red node self is less that whole tree.\n\nBTW, we do not need calculate whole tree size because we got it from input parameters as `n` parameter. \n\n\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n \n def sub_tree_size(node ):\n if node is None:\n return 0 \n return sub_tree_size(node.left) + sub_tree_size(node.right) + 1 \n \n def find_red(root, x):\n q = [root]\n while len(q):\n node = q.pop()\n if node.val == x:\n return node\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n \n red_node = find_red(root,x)\n l_tree_size = sub_tree_size(red_node.left)\n r_tree_size = sub_tree_size(red_node.right)\n red_size = l_tree_size + r_tree_size +1\n is_red_root = red_node == root\n \n # use left\n if n - l_tree_size <l_tree_size:\n return True\n # use right \n if n - r_tree_size < r_tree_size:\n return True\n # use parent \n if is_red_root !=True and n - red_size >red_size:\n return True \n return False \n \n```
1
0
[]
0
binary-tree-coloring-game
JAVA | DFS + DP + Greedy | 100% |
java-dfs-dp-greedy-100-by-idbasketball08-o97b
\nclass Solution {\n //these are the vals of the left and right node of x\n public int left = -1, right = -1;\n public boolean btreeGameWinningMove(Tre
idbasketball08
NORMAL
2021-01-18T00:41:31.105955+00:00
2021-01-18T00:41:52.263439+00:00
101
false
```\nclass Solution {\n //these are the vals of the left and right node of x\n public int left = -1, right = -1;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n //strategy: DFS + DP + Greedy\n //try to block the 3 neighbors that player 1 chooses\n //dp[i] means all of the nodes below node i and itself\n int[] dp = new int[n + 1];\n dfs(root, dp, x);\n //figure out the amt of nodes in the left and right node of x\n left = (left == -1) ? 0 : dp[left];\n right = (right == -1) ? 0 : dp[right];\n //the amt of nodes for the parent of x is just the remaining nodes that are not left or right or x\n //if any of these amt are more than half then choose that node and we win\n return Math.max(left, Math.max(right, n - left - right - 1)) > n / 2;\n }\n private int dfs(TreeNode root, int[] dp, int x) {\n //reached end \n if (root == null) {\n return 0;\n }\n //seen before so use that amt\n if (dp[root.val] != 0) {\n return dp[root.val];\n }\n if (root.val == x) {\n //find the left and right val of node x\n left = (root.left != null) ? root.left.val : -1;\n right = (root.right != null) ? root.right.val : -1;\n }\n //total nodes are all the nodes to left and right and itself\n return dp[root.val] = dfs(root.left, dp, x) + dfs(root.right, dp, x) + 1;\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
Java simple solution- one bottom up recursion
java-simple-solution-one-bottom-up-recur-mvx9
\'\'\'\nclass Solution {\n int left;\n int right;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if(root==null) return f
uzya
NORMAL
2020-10-06T03:30:56.684014+00:00
2020-10-06T03:30:56.684058+00:00
135
false
\'\'\'\nclass Solution {\n int left;\n int right;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if(root==null) return false;\n dfs(root, x);\n //should see where to block , which node of x\'s left, right or parent\n //the part with most nodes. part including parent does have number of\n //n-left-right-1 nodes. max part should have more than n/2 to win.\n return Math.max(n-left-right-1, Math.max(left, right)) > n/2;\n }\n \n public int dfs(TreeNode root, int x){\n \n if(root==null) return 0;\n \n int l=dfs(root.left, x);\n int r=dfs(root.right, x);\n \n if(root.val==x){\n left=l;\n right=r;\n }\n \n return l+r+1;\n }\n}\n\'\'\'
1
0
[]
0
binary-tree-coloring-game
C++ beat 100%
c-beat-100-by-shuqi7-eguy
\nTreeNode *find(TreeNode *node, int x) {\n\tif (node == NULL) return NULL;\n\tif (node->val == x) return node;\n\tTreeNode *left = find(node->left, x);\n\tTree
shuqi7
NORMAL
2020-09-27T15:44:46.386641+00:00
2020-09-27T15:44:46.386672+00:00
165
false
```\nTreeNode *find(TreeNode *node, int x) {\n\tif (node == NULL) return NULL;\n\tif (node->val == x) return node;\n\tTreeNode *left = find(node->left, x);\n\tTreeNode *right = find(node->right, x);\n\tif (left != NULL) return left;\n\treturn right;\n}\n\nint count(TreeNode *node) {\n\tif (node == NULL) return 0;\n\treturn 1 + count(node->left) + count(node->right);\n}\n\nbool btreeGameWinningMove(TreeNode* root, int n, int x) {\n\tTreeNode *node = find(root, x);\n\tint countLeft = count(node->left);\n\tint countRight = count(node->right);\n\tint rest = n - countLeft - countRight - 1;\n\treturn countLeft>(countRight+rest) || countRight>(rest+countLeft) || rest>(countLeft+countRight);\n}\n\n```
1
0
[]
0
binary-tree-coloring-game
Javascript Easy Solution With Clear Explanation [DFS]
javascript-easy-solution-with-clear-expl-9h84
Okay so the solution to this problem is that we can win on 2 conditions:\n If the player has chosen a node where entire sum of all the nodes in the subtree for
james2allen
NORMAL
2020-09-14T17:26:49.629579+00:00
2020-09-14T17:28:56.290313+00:00
184
false
Okay so the solution to this problem is that we can win on 2 conditions:\n* If the player has chosen a node where entire sum of all the nodes in the subtree for their chosen node is less than the sum of the remainder nodes, you will easily win in this case by choosing the parent node to their tree and cutting them off.\n* If the left or right subtree of the node they chose contains more nodes than the rest of the remainder nodes, you will then win by chosing the left or right child node and cutting them off.\n\nIf none of the above conditions are true, you return false.\n\n```\nvar btreeGameWinningMove = function(root, n, x) {\n let queue = [root], parents = [];\n let temp = root;\n\t\n\t// find the node that has be chosen using dfs\n while(temp.val !== x) {\n temp = queue.shift();\n temp.left ? queue.push(temp.left) : null;\n temp.right? queue.push(temp.right): null;\n }\n \n // get the sum of all the nodes in the sub tree using dfs\n let getSubtreeSum = (node) => {\n if(!node) {\n return 0;\n }\n let q = [node];\n let sub, count = 0;\n while(q.length) {\n count++;\n sub = q.shift();\n sub.left ? q.push(sub.left) : null;\n sub.right? q.push(sub.right): null;\n }\n return count;\n }\n \n\t// get the sums of both child trees\n let leftSum = getSubtreeSum(temp.left), rightSum = getSubtreeSum(temp.right);\n \n\t// if the sum of all the nodes in the tree that the other player picked can be cut off, and is less than\n\t// the remainder return true\n if( n - (leftSum + rightSum + 1 ) > leftSum + rightSum + 1){\n return true;\n }\n \n\t// If one of the child nodes presents itself as a larger tree than the remainder count of nodes return true\n if(leftSum > n - leftSum || rightSum > n-rightSum) {\n return true;\n }\n \n\t// return false if none of these conditions can be met\n return false;\n \n \n};
1
0
['Depth-First Search', 'JavaScript']
0
binary-tree-coloring-game
My O(n) Solution | Accepted | Java | Beats 100%
my-on-solution-accepted-java-beats-100-b-5ur0
\nclass Solution {\n int left = 0, right = 0;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n \n helper(root, x);\n
Bhavyaa_Arora_08
NORMAL
2020-08-18T13:34:37.305754+00:00
2020-08-18T13:34:37.305917+00:00
77
false
```\nclass Solution {\n int left = 0, right = 0;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n \n helper(root, x);\n int o = n - left - right -1 ;\n return left > n/2 || right > n/2 || o > n/2;\n \n }\n \n public int helper(TreeNode node, int x){\n if(node == null) return 0;\n \n int l = helper(node.left, x);\n int r = helper(node.right, x);\n \n if(node.val == x){\n left = l;\n right = r;\n }\n \n return l + r + 1;\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
c++ BFS
c-bfs-by-sahlot01-rtt3
\nint solve(TreeNode*node){\n if(node==NULL) return 0;\n int cnt=1;\n cnt+=solve(node->left);\n cnt+=solve(node->right);\n return cnt;\n}\n\nclas
sahlot01
NORMAL
2020-08-01T06:39:40.727548+00:00
2020-08-01T06:39:40.727597+00:00
107
false
```\nint solve(TreeNode*node){\n if(node==NULL) return 0;\n int cnt=1;\n cnt+=solve(node->left);\n cnt+=solve(node->right);\n return cnt;\n}\n\nclass Solution {\npublic:\n bool btreeGameWinningMove(TreeNode* node, int k, int x) {\n queue<TreeNode*>q;\n q.push(node);\n TreeNode*n;\n while(!q.empty()){\n n=q.front();\n q.pop();\n if(n->val==x) break;\n if(n->left) q.push(n->left);\n if(n->right) q.push(n->right);\n }\n int leftcnt=solve(n->left);\n int rightcnt=solve(n->right);\n int upcnt=k-(leftcnt+rightcnt+1);\n if(upcnt > rightcnt+leftcnt+1) return true;\n if(leftcnt > rightcnt+upcnt+1) return true;\n if(rightcnt > leftcnt+upcnt+1) return true;\n return false;\n }\n};\n```
1
0
[]
0
binary-tree-coloring-game
Python with explanation O(N)
python-with-explanation-on-by-rambhagwan-3y6k
You need to make yourself belive that 2nd player will only try to take either left node of x or right node of x or parent node of x:\nif 2nd playes takes left n
rambhagwan
NORMAL
2020-07-28T07:27:28.162504+00:00
2020-07-28T07:27:28.162555+00:00
182
false
You need to make yourself belive that 2nd player will only try to take either left node of x or right node of x or parent node of x:\nif 2nd playes takes left node of x:\n\tthen he can capture all nodes in this subtree. player 1 will capture all nodes nodes except these.\nif 2nd playes takes right node of x:\n\tthen he can capture all nodes in this subtree. player 1 will capture all nodes nodes except these.\nif 2nd playes takes parent node of x:\n\tthen he can capture all nodes except x and its subtrees.\nSo we calculate nodes in left subtree of x, nodes in left subtree of x, node except x and its subtree. \n\n```\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n def fun(root): #fun counts the node in subtree with root as node\n if not root: return 0\n return 1+fun(root.left)+fun(root.right)\n arr = [0,0]\n def f(root):\n if root:\n if root.val == x:\n arr[0] = fun(root.left)\n arr[1] = fun(root.right)\n return\n else:\n f(root.left)\n f(root.right)\n f(root)\n # print(arr)\n y = max(arr[0], arr[1], n-arr[0]-arr[1]-1)\n return y > n//2
1
0
[]
0
binary-tree-coloring-game
JAVA EASIEST 0 ms
java-easiest-0-ms-by-gauravsethia-weyv
\nclass Solution {\n int left, right;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if(n==1)\n return false;\n
gauravsethia
NORMAL
2020-07-19T17:58:00.892021+00:00
2020-07-19T17:58:00.892070+00:00
135
false
```\nclass Solution {\n int left, right;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if(n==1)\n return false;\n if(n==2)\n return false;\n if(n==3)\n {\n if(x!=1)\n return true;\n return false;\n }\n count(root,x);\n if(left+right+1<n/2)\n return true;\n if((left>n/2)||(right>n/2))\n return true;\n return false;\n }\n\n private int count(TreeNode node,int x) {\n if (node == null) return 0;\n int l = count(node.left,x), r = count(node.right,x);\n if (node.val == x) {\n left = l;\n right = r;\n }\n return l + r + 1;\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
JAVA easy to understand solution
java-easy-to-understand-solution-by-jian-bg2s
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n
jianhuilin1124
NORMAL
2020-06-22T03:36:33.687504+00:00
2020-06-22T03:36:33.687554+00:00
240
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n TreeNode node = findNode(root, x);\n n /= 2;\n int l = countNodes(node.left);\n if (l > n)\n return true;\n int r = countNodes(node.right);\n if (r > n)\n return true;\n int p = countNodes(node);\n if (p > n)\n return false;\n return true;\n }\n \n private int countNodes(TreeNode node){\n if (node == null)\n return 0;\n return countNodes(node.left) + countNodes(node.right) + 1;\n }\n \n private TreeNode findNode(TreeNode node, int x){\n if (node == null || node.val == x)\n return node;\n TreeNode l = findNode(node.left, x);\n TreeNode r = findNode(node.right, x);\n return l == null ? r : l;\n }\n}\n```
1
0
['Java']
0
binary-tree-coloring-game
Python Concise O(n) Solution (Beats 90%)
python-concise-on-solution-beats-90-by-z-eono
There are 3 best choices depending on the node the first player chose:\n1. The node\'s left child.\n2. The node\'s right child.\n3. The node\'s parent.\n\nFor e
zlax
NORMAL
2020-06-20T10:40:54.395253+00:00
2020-06-20T10:43:03.334335+00:00
146
false
There are 3 best choices depending on the node the first player chose:\n1. The node\'s left child.\n2. The node\'s right child.\n3. The node\'s parent.\n\nFor each choice, our best size is the size of that subtree (if it\'s the parent, its the total nodes - nodes rooted at the 1st player\'s node). The other player gets the rest of nodes that you didn\'t choose.\nCompare all 3 choices and choose the one that would take more nodes than the 1st player.\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n parentSize = self.getSize(root, x)\n node = self.getNode(root, x)\n leftSize = self.getSize(node.left, None)\n rightSize = self.getSize(node.right, None)\n \n win1 = parentSize > leftSize + rightSize + 1\n win2 = leftSize > parentSize + rightSize + 1\n win3 = rightSize > leftSize + parentSize + 1\n \n return win1 or win2 or win3\n \n \n def getSize(self, node, stopNode):\n if not node or node.val == stopNode:\n return 0\n \n return 1 + self.getSize(node.left, stopNode) + self.getSize(node.right, stopNode)\n\n def getNode(self, root, n):\n if not root:\n return None\n if root.val == n:\n return root\n \n return self.getNode(root.left, n) or self.getNode(root.right, n)\n```
1
0
[]
0
binary-tree-coloring-game
Java easy to understand solution
java-easy-to-understand-solution-by-hema-g8eg
My algorithm:\n1. Find the node with value x\n2. Calculate number of nodes in the left and right sub trees of x\n3. n - (leftCount + rightCount + 1) will give r
hemanthreddy
NORMAL
2020-06-16T09:40:41.723577+00:00
2020-06-16T09:43:55.350090+00:00
115
false
My algorithm:\n1. Find the node with value `x`\n2. Calculate number of nodes in the left and right sub trees of `x`\n3. `n - (leftCount + rightCount + 1)` will give remaining subtree node count.\n4. Check if one of the above 3 subtrees has node count greater than the sum of remaining two.\n\n```\nclass Solution {\n int nodeCount(TreeNode root) {\n if (root == null) return 0;\n return 1 + nodeCount(root.left) + nodeCount(root.right);\n }\n\n TreeNode find(TreeNode root, int x) {\n if (root == null) return null;\n if (root.val == x) return root;\n TreeNode left = find(root.left, x);\n if (left != null) return left;\n return find(root.right, x);\n }\n\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if (root == null) return false;\n TreeNode p1Node = find(root, x);\n int leftCount = nodeCount(p1Node.left);\n int rightCount = nodeCount(p1Node.right);\n int remCount = n - (leftCount + rightCount + 1);\n if (remCount > (leftCount + rightCount + 1) ||\n leftCount > (remCount + rightCount + 1) ||\n rightCount > (remCount + leftCount + 1)) {\n return true;\n }\n return false;\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
Python | O(n) simple
python-on-simple-by-somanish-d3dz
We are interested in number of left and right child the X node has. Our case of winning is in either of 2 scenarios:\n1. I get any child (left or right) with ma
somanish
NORMAL
2020-06-07T21:21:57.242633+00:00
2020-06-07T21:21:57.242677+00:00
104
false
We are interested in number of left and right child the X node has. Our case of winning is in either of 2 scenarios:\n1. I get any child (left or right) with majority of nodes then I can block his coloring\n2. If parent has majority, I can select parent to block other half from red color\n```\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n val = []\n \n def traverse(node: TreeNode):\n nonlocal x,val\n if not node: return 0\n \n l = traverse(node.left)\n r = traverse(node.right)\n if node.val == x: val = [l,r]\n \n return l+r+1\n \n traverse(root)\n l,r = val\n \n #Either child has majority or select parent for majority\n return True if max(l,r) > n//2 or l+r+1 <= n//2 else False \n```
1
0
[]
0
binary-tree-coloring-game
cpp solution
cpp-solution-by-_mrbing-bofd
//I will win the game when when I choose a node in neighbour of x that has maximum number of nodes so that i will have more nodes to color if l is left neighb
_mrbing
NORMAL
2020-05-30T04:59:59.583637+00:00
2020-05-30T04:59:59.583679+00:00
86
false
//I will win the game when when I choose a node in neighbour of x that has maximum number of nodes so that i will have more nodes to color if l is left neighbour , r is right neighbour and u is upper neighbour then either of the below three should be true l > r+u || r > l+u || u > l+r whichever is true we\'ll choose that neighbour otherwise we will loose the game\n\nRuntime: 4 ms, faster than 80.55% of C++ online submissions for Binary Tree Coloring Game.\nMemory Usage: 10.9 MB, less than 100.00% of C++ online submissions for Binary Tree Coloring Game.\n```\nclass Solution {\n int count(TreeNode* root){\n if(!root){\n return 0;\n }\n return 1+count(root->left)+count(root->right);\n }\n TreeNode* find(TreeNode* root, int x){\n if(!root){\n return NULL;\n }\n if(root->val == x){\n return root;\n }\n TreeNode * left = find(root->left,x);\n if(left == NULL){\n return find(root->right, x);\n } \n return left;\n }\npublic:\n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n int total = count(root);\n TreeNode* red = find(root,x);\n if(red == NULL){\n return true;\n }\n int left = count(red->left);\n int right = count(red->right);\n int up = n - left - right - 1;\n if((up > left + right) || (left > up + right) || (right > up + left)){\n return true;\n }\n return false;\n }\n};
1
0
[]
0
binary-tree-coloring-game
JAVA 100% 100% With explanation
java-100-100-with-explanation-by-betterc-vmd8
\t//find node in leftSubTree,then in rightSubTree ,then find leftNodeCount\n\t//if max of above 3 is greater than n/2 return true \n\tclass Solution {\n\t\tpubl
bettercallavi
NORMAL
2020-05-24T08:06:23.476291+00:00
2020-05-24T08:06:23.476349+00:00
159
false
\t//find node in leftSubTree,then in rightSubTree ,then find leftNodeCount\n\t//if max of above 3 is greater than n/2 return true \n\tclass Solution {\n\t\tpublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n\t\t\tTreeNode node=find(root,x);\n\t\t\tint countLeft=count(node.left);\n\t\t\tint countRight=count(node.right);\n\t\t\tint leftNodeCount=n-countLeft-countRight-1;\n\t\t\tint max=Math.max(leftNodeCount,Math.max(countLeft,countRight));\n\t\t return max>((n/2))? true:false; \n\t\t}\n\t\t//method to count number of node in a subtree \n\t\tint count(TreeNode node){\n\t\t\t if(node==null)\n\t\t\t\treturn 0;\n\t\t return 1+count(node.left)+count(node.right); \n\t\t}\n\t\t//method to find node\n\t\tTreeNode find(TreeNode node,int n){\n\t\t\tif(node==null)\n\t\t\t\treturn null;\n\t\t\tif(node.val==n)\n\t\t\t\treturn node;\n\t\t TreeNode left=find(node.left,n);\n\t\t TreeNode right=find(node.right,n);\n\t\t\treturn left==null? right:left;\n\t\t}\n\t}
1
0
[]
0
binary-tree-coloring-game
Easy O(n) JAVA DFS solution
easy-on-java-dfs-solution-by-legendaryen-abkp
\nclass Solution {\n private int leftCount;\n private int rightCount;\n \n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n
legendaryengineer
NORMAL
2020-04-25T23:53:11.040429+00:00
2020-04-25T23:53:11.040485+00:00
103
false
```\nclass Solution {\n private int leftCount;\n private int rightCount;\n \n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n find(root, x);\n int red = 1 + leftCount + rightCount;\n if (n - red > red || leftCount > n - leftCount || rightCount > n - rightCount) return true;\n return false;\n }\n \n private boolean find(TreeNode node, int target) {\n if (node == null) return false;\n if (node.val == target) {\n leftCount = getCount(node.left);\n rightCount = getCount(node.right);\n return true;\n } else {\n if (find(node.left, target)) return true;\n if (find(node.right, target)) return true;\n return false;\n }\n }\n \n private int getCount(TreeNode node) {\n if (node == null) return 0;\n return 1 + getCount(node.left) + getCount(node.right);\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
C++ dfs
c-dfs-by-wufengxuan1230-4ltq
\nclass Solution {\npublic:\n int parent = 0;\n int left = 0;\n int right = 0;\n \n int traverse(TreeNode* root, int x)\n {\n if(root)\
wufengxuan1230
NORMAL
2020-04-14T12:39:29.693875+00:00
2020-04-14T12:39:41.808444+00:00
160
false
```\nclass Solution {\npublic:\n int parent = 0;\n int left = 0;\n int right = 0;\n \n int traverse(TreeNode* root, int x)\n {\n if(root)\n {\n int l = traverse(root->left, x);\n int r = traverse(root->right, x);\n \n if(root->val == x)\n left = l, right = r;\n \n return 1 + l + r;\n }\n return 0;\n }\n \n bool btreeGameWinningMove(TreeNode* root, int n, int x) \n {\n traverse(root, x);\n parent = n - left - right - 1;\n return left > (parent + right) || right > (parent + left) || parent > (left + right);\n }\n};\n```
1
0
[]
0
binary-tree-coloring-game
Python3 82.89% (28 ms)/100.00% (13.8 MB) -- O(n) time/O(h) space (recursion) -- 3 counters
python3-8289-28-ms10000-138-mb-on-timeoh-4m4c
\nclass Solution:\n def count_nodes(self, node, counters, index, x):\n if (node):\n if (node.val == x):\n self.count_nodes(n
numiek_p
NORMAL
2020-04-02T21:13:22.703545+00:00
2020-04-02T21:13:22.703593+00:00
92
false
```\nclass Solution:\n def count_nodes(self, node, counters, index, x):\n if (node):\n if (node.val == x):\n self.count_nodes(node.left, counters, 1, x)\n self.count_nodes(node.right, counters, 2, x)\n else:\n counters[index] += 1\n self.count_nodes(node.left, counters, index, x)\n self.count_nodes(node.right, counters, index, x)\n \n \n \n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n counters = [0, 0, 0]\n self.count_nodes(root, counters, 0, x)\n counters.sort()\n return counters[2] > 1 + counters[1] + counters[0]\n```
1
0
[]
0
binary-tree-coloring-game
Java Simple BFS
java-simple-bfs-by-hobiter-rn78
\nclass Solution {\n int left, right, x;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n this.x = x;\n dfs(root);
hobiter
NORMAL
2020-03-15T06:14:31.839937+00:00
2020-03-15T17:58:11.273860+00:00
198
false
```\nclass Solution {\n int left, right, x;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n this.x = x;\n dfs(root); \n return Math.max(Math.max(left, right), n - left - right - 1) > n / 2;\n }\n \n private int dfs(TreeNode node) {\n if (node == null) return 0;\n int l = dfs(node.left);\n int r = dfs(node.right);\n if (node.val == x) {\n left = l;\n right = r;\n }\n return l + r + 1;\n }\n}\n```\nRef: https://leetcode.com/problems/binary-tree-coloring-game/discuss/350570/JavaC%2B%2BPython-Simple-recursion-and-Follow-Up\n
1
0
[]
1
binary-tree-coloring-game
[C++] 0ms | Time O(N) | Space O(H) | Simple
c-0ms-time-on-space-oh-simple-by-dhdnr12-0day
\nclass Solution {\nprivate:\n int p1,pl,pr,X;\npublic:\n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n if (n == 1) return false;\n
dhdnr1220
NORMAL
2020-02-13T14:50:13.519060+00:00
2020-02-13T14:50:13.519094+00:00
132
false
```\nclass Solution {\nprivate:\n int p1,pl,pr,X;\npublic:\n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n if (n == 1) return false;\n p1 = pl = pr = 0; X = x;\n dfs(root);\n return (n - p1 > p1) || (pl > n - pl) || (pr > n - pr); \n }\n \n int dfs(TreeNode* n) {\n if (n == NULL) return 0;\n if (n->val == X) {\n pl = dfs(n->left); pr = dfs(n->right);\n p1 = pl + pr + 1;\n return p1;\n } \n return dfs(n->left) + dfs(n->right) + 1;\n }\n};\n```
1
0
[]
0
binary-tree-coloring-game
Java simple solution beats 100% time & space with explanation
java-simple-solution-beats-100-time-spac-zcxs
\nclass Solution {\n private int left, right, val;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n val = x; left =0; right =
akiramonster
NORMAL
2019-12-31T17:30:48.044886+00:00
2019-12-31T17:30:48.044956+00:00
148
false
```\nclass Solution {\n private int left, right, val;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n val = x; left =0; right = 0;\n count(root);\n return left > n/2 || right > n/2 || (left + right +1) < (n+1)/2;\n }\n \n private int count(TreeNode root){\n if(root == null) return 0;\n int l = count(root.left);\n int r = count(root.right);\n if(root.val == val){\n left = l;\n right = r;\n }\n return l + r +1;\n }\n}\n\n/*\ncountLeft, countRight of x\n\nif(countLeft or countRight > n/2) return true. Because we choose one of child whose count > n/2\nif(countLeft + countRight +1 < n/2) return true. Because we choose parent of x\n\nother return false;\n\n*/\n```
1
0
[]
0
binary-tree-coloring-game
Easy DFS C++ Solution
easy-dfs-c-solution-by-codhek-fvdt
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : v
codhek
NORMAL
2019-12-29T18:00:22.909359+00:00
2019-12-29T18:00:22.909394+00:00
216
false
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n vector <int> graph[105];\n set <int> vis;\n int size = 0;\n \n void build(TreeNode *root) {\n if(!root) return;\n \n if(root->left) {\n graph[root->val].push_back(root->left->val);\n graph[root->left->val].push_back(root->val);\n }\n if(root->right) {\n graph[root->val].push_back(root->right->val);\n graph[root->right->val].push_back(root->val);\n }\n \n build(root->left);\n build(root->right);\n }\n \n void dfs(int node, int x) {\n vis.insert(node);\n size += 1;\n \n for(int i=0;i<graph[node].size();i++) {\n if(vis.find(graph[node][i]) == vis.end() && graph[node][i] != x) {\n dfs(graph[node][i], x);\n }\n } \n }\n \n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n build(root);\n \n int maxSubtree = -1;\n for(int i=0;i<graph[x].size();i++) {\n dfs(graph[x][i], x);\n maxSubtree = max(maxSubtree, size);\n size = 0;\n }\n \n return (n - maxSubtree) < maxSubtree;\n }\n};\n```
1
0
['Depth-First Search', 'C']
0
binary-tree-coloring-game
java recursion O(n) time O(h) space, beats 100%
java-recursion-on-time-oh-space-beats-10-cvyh
\n/*\nthe problem is same as seeing if can count # of nodes from x.left, or x.right, or x.parent, such that we can count # of nodes, ycount, such that ycount >
makotobot98
NORMAL
2019-12-26T21:13:34.245108+00:00
2019-12-26T21:13:34.245144+00:00
100
false
```\n/*\nthe problem is same as seeing if can count # of nodes from x.left, or x.right, or x.parent, such that we can count # of nodes, ycount, such that ycount > n - ycount\n\nthe reason for this intuition is that any node acts as a path block, meaning we pick any node i, then depends on the opponent node j, either left subtree, right subtree or the parent subtree of i will be a path block\n\nalgorithm: it\'s simply a variation of count # nodes in a given tree\n1. locate node with value x\n *if root.val == x, we can only split tree into left, or right. so no need to count parent tree\n2. count nodes in x.left, x.right, x.parent respectively\n3. validate if any ycount > n - ycount, or equivalently, 2*ycount > n\n\ntime: O(n)\nspcae: O(height) for recursion stack\n*/\nclass Solution {\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n if (root == null) {\n return true;\n }\n \n if (root.val == x) {\n return (2 * count(root.left, -1) > n) || (2 * count(root.right, -1) > n); \n }\n \n //root is not x\n TreeNode xnode = locate(root, x);\n int nparent = count(root, x);\n if (2 * nparent > n) {\n return true;\n }\n int nleft = count(xnode.left, -1);\n if (2 * nleft > n) {\n return true;\n }\n int nright = count(xnode.right, -1);\n if (2 * nright > n) {\n return true;\n }\n return false;\n }\n //count # of nodes, if meet t, return. t is the node where we should stop counting that subtree, node t should not be counted either\n public int count(TreeNode root, int t) {\n if (root == null || root.val == t) {\n return 0;\n }\n int left = count(root.left, t);\n int right = count(root.right, t);\n return left + right + 1;\n }\n //return target node x, given root node\n public TreeNode locate(TreeNode root, int x) {\n if (root == null || root.val == x) {\n return root;\n }\n TreeNode left = locate(root.left, x);\n if (left != null) {\n return left;\n }\n TreeNode right = locate(root.right, x);\n return right;\n }\n \n}\n```
1
0
[]
0
binary-tree-coloring-game
Javascript 4 line solution
javascript-4-line-solution-by-liushuaima-rte0
```js\nvar btreeGameWinningMove = function(root, n, x) {\n const count = root => root ? count(root.left) + count(root.right) + 1 : 0;\n const find = root
liushuaimaya
NORMAL
2019-12-24T12:13:03.332785+00:00
2019-12-24T12:17:46.795853+00:00
172
false
```js\nvar btreeGameWinningMove = function(root, n, x) {\n const count = root => root ? count(root.left) + count(root.right) + 1 : 0;\n const find = root => root ? root.val === x && root || find(root.left) || find(root.right) : false;\n const node = find(root), l = count(node.left), r = count(node.right), p = n - l - r - 1, max = Math.max(l, r, p);\n return max > n - max;\n};
1
1
['JavaScript']
0
binary-tree-coloring-game
Explanation for recursive & short C# [100% speed and memory]
explanation-for-recursive-short-c-100-sp-o1jt
Fairly simple.\n\n Since we\'re following the parent pointer, treat the binary tree as a graph\n The x divides the graph into at most 3 subgraphs (left, right,
lano1
NORMAL
2019-12-21T20:19:20.686746+00:00
2019-12-21T20:26:46.429817+00:00
141
false
Fairly simple.\n\n* Since we\'re following the parent pointer, treat the binary tree as a graph\n* The ```x``` divides the graph into at most 3 subgraphs (left, right, parent)\n* The optimal move is to play adjacent to ```x``` so we can colour one of the three subgraph \n* If any one of the 3 subgraphs has a count greater than the sum of the other two, then we can win\n\n----\n\n* Get a reference to the node with value ```x```\n* Calculate the counts of the left and right subtree\n* Skip turning the solution into a graph problem via maths: parentCount = ```n``` - (dividing node + count(left) + count(right))\n* Check to see if any of the counts is larger than the sum of the other two\n\n```\npublic bool BtreeGameWinningMove(TreeNode root, int n, int x)\n{\n int Count(TreeNode node) => node == null ? 0 : Count(node.left) + Count(node.right) + 1;\n\n TreeNode Find(TreeNode current, int needle) \n {\n if (current == null) { return null; }\n if (needle == current.val) { return current; }\n return Find(current.left, needle) ?? Find(current.right, needle);\n }\n\n TreeNode main = Find(root, x);\n int leftCount = Count(main.left), rightCount = Count(main.right);\n int parentCount = n - (leftCount + rightCount + 1);\n\n return parentCount > (leftCount + rightCount) || \n leftCount > (parentCount + rightCount) || \n rightCount > (leftCount + parentCount);\n}\n```\n\nRuntime: 84 ms, faster than 100.00% of C# online submissions for Binary Tree Coloring Game.\nMemory Usage: 23.7 MB, less than 100.00% of C# online submissions for Binary Tree Coloring Game.
1
0
['Binary Tree']
0
binary-tree-coloring-game
Java Simple Code 100% time and 100% memory with explanation.
java-simple-code-100-time-and-100-memory-ox74
Suppose the first player marked node x. The main concept is, being a second player, we can stop the first player from expanding by either marking the parent of
pramitb
NORMAL
2019-12-21T12:49:37.529900+00:00
2019-12-21T12:49:37.529945+00:00
102
false
Suppose the first player marked node ***x***. The main concept is, being a second player, we can stop the first player from expanding by either marking the parent of ***x***, right child of ***x*** or the left child of ***x***. So, let\'s count the number of nodes in the left subtree of the node ***x*** as ***cl*** and count the number of nodes in the right subtree of the node ***x*** as ***cr***. Subtracting this from the total number of nodes and reducing the result by 1, we can get the number of nodes present in the tree but not in the subtree of which ***x*** is the root, as ***z***. The variables ***z***, ***cl*** and ***cr*** stores the number of nodes we can get if we mark the parent, left child or right child of ***x*** respectively. We can win if either one of the variables is greater than the sum of the other two added with 1. 1 is added to exclude the temp node itself.\n```\nclass Solution {\n int cl,cr;\n TreeNode temp;\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n cl=0;\n cr=0;\n temp=null;\n if(root==null)\n return false; // we cannot win if there is no tree.\n search(root,x); // to search the node with value x in the tree.\n if(temp==null)\n return true; // if the node is not present we will always win marking the root of the original tree.\n dfs(temp.left,true);// to count nodes in left subtree.\n dfs(temp.right,false);// to count nodes in right subtree.\n int z=n-cl-cr-1;// to count nodes present in original tree but not in the subtree of which node(temp) with value x is the root.\n return (z>cl+cr+1)||(cl>z+cr+1)||(cr>z+cl+1); // if either one of the variables is greater than the sum of the other two added with 1. \n\t\t// 1 is added to exclude the temp node itself.\n }\n public void dfs(TreeNode root,boolean f){\n\t// f is true for left subtree and false for right subtree.\n if(root==null)\n return;\n if(f)\n cl++;\n else\n cr++;\n dfs(root.left,f);\n dfs(root.right,f);\n }\n public void search(TreeNode root,int x){\n\t// for searching the node with value x by dfs.\n if(root==null)\n return;\n if(temp!=null)\n return;\n if(root.val==x){\n temp=root;\n return;\n }\n search(root.left,x);\n search(root.right,x); \n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
python -- O(N)
python-on-by-ht_wang-vkis
\ndef btreeGameWinningMove(self, root, n, x):\n """\n :type root: TreeNode\n :type n: int\n :type x: int\n :rtype: bool\n
ht_wang
NORMAL
2019-12-17T06:02:30.701289+00:00
2019-12-17T06:02:30.701349+00:00
117
false
```\ndef btreeGameWinningMove(self, root, n, x):\n """\n :type root: TreeNode\n :type n: int\n :type x: int\n :rtype: bool\n """\n self.l, self.r = None, None\n def numNodes(root, x):\n if not root:\n return 0 \n l = numNodes(root.left, x)\n r = numNodes(root.right, x)\n if root.val ==x:\n self.l = l\n self.r = r\n return l+r+1\n numNodes(root,x)\n return max(self.l, self.r, n-self.l-self.r-1)>n/2\n```
1
0
[]
0
binary-tree-coloring-game
Java (100% / 100%)
java-100-100-by-benlu1117-lohu
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x)
benlu1117
NORMAL
2019-12-11T01:04:10.775878+00:00
2019-12-11T01:04:10.775915+00:00
97
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n \n // after first player choose, the second play can have 3 options, choose parent, left or right so that he can block the frist player from choose the subtree of the node that second player choose\n \n private int countL, countR;\n \n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n helper(root, x, false, false);\n int countP = n - countL - countR - 1;\n return countL * 2 > n || countR * 2 > n || countP * 2 > n;\n }\n \n \n private void helper(TreeNode root, int x, boolean isXLeft, boolean isXRight) {\n if (root == null) return;\n \n if (isXLeft) {\n countL++;\n } else if (isXRight) {\n countR++;\n }\n \n if (root.val == x) {\n helper(root.left, x, true, false);\n helper(root.right, x, false, true);\n } else {\n helper(root.left, x, isXLeft, isXRight);\n helper(root.right, x, isXLeft, isXRight);\n }\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
JAVA DFS
java-dfs-by-jwang89225-w98d
\nThe first step is to find the node with value x. \nThe node will split whole tree into at almost three subtrees. \n \n node x \'s left subtree, \n node x\
jwang89225
NORMAL
2019-11-22T14:40:27.675235+00:00
2019-11-22T14:40:27.675269+00:00
148
false
\nThe first step is to find the node with value x. \nThe node will split whole tree into at almost three subtrees. \n ```\n node x \'s left subtree, \n node x\' s right subtree, \n the rest of subtree from node\'x parent \n```\n \n If parent of node x is null, which means the node x is root node. At this scenario, we only need to check if number of left subtree and number of right subtree are equal. Because we assume players are very intelligent , and they will always try with bigger tree, then block this tree.\n \n If parent exists, there are three subtrees. the second player will win if there is a tree whose number of nodes are larger than sum of number of nodes of rest two tree trees.\n \n ` \n int sum = parentNumber + leftNumber + rightNumber;\n int max = Math.max(parentNumber, Math.max(leftNumber, rightNumber));\n return max > sum - max;\t\t\n`\n\nBecause we need to know the amount of each subtree, so I will use a \n```\nMap<TreeNode, Integer> counts \n```\nto store number of children of each node during DFS process.\n\n```\npublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n Map<TreeNode, Integer> counts = new HashMap<TreeNode, Integer>();\n TreeNode node = dfs(root, x, counts);\n if (node == null) {\n return false;\n }\n int parentNumber = n - counts.get(node);\n int leftNumber = node.left == null ? 0 : counts.get(node.left);\n int rightNumber = node.right == null ? 0: counts.get(node.right);\n int sum = parentNumber + leftNumber + rightNumber;\n int max = Math.max(parentNumber, Math.max(leftNumber, rightNumber));\n return max > sum - max;\n\n }\n \n private TreeNode dfs(TreeNode root, int n, Map<TreeNode, Integer> counts) {\n if (root == null) {\n return null;\n }\n int sum = 1;\n TreeNode left = dfs(root.left, n, counts);\n TreeNode right = dfs(root.right, n, counts);\n if (root.left != null) {\n sum += counts.getOrDefault(root.left, 0);\n }\n \n if (root.right != null) {\n sum += counts.getOrDefault(root.right, 0);\n }\n \n counts.put(root, sum);\n if (left != null) {\n return left;\n } else if (right != null) {\n return right;\n } else if (root.val == n) {\n return root;\n } else {\n return null;\n }\n }\n```\n\n
1
0
['Depth-First Search']
0
binary-tree-coloring-game
Python greedy solution
python-greedy-solution-by-loickenleetcod-sf49
To block x player, we only consider xnode\'s parent node or it\'s two children nodes as y node.\n\n def btreeGameWinningMove(self, root: TreeNode, n: int, x:
loickenleetcode
NORMAL
2019-10-29T07:31:34.007386+00:00
2019-10-29T07:31:34.007420+00:00
98
false
To block x player, we only consider xnode\'s parent node or it\'s two children nodes as y node.\n```\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n def find(root, x):\n if not root:\n return\n if root.val == x:\n return root\n \n return find(root.left, x) or find(root.right, x)\n \n xnode = find(root, x)\n \n def count(node):\n if not node:\n return 0\n return 1 + count(node.left) + count(node.right)\n \n l, r = count(xnode.left), count(xnode.right)\n return n-l-r-1 > (l+r+1) or l > n-l or r > n - r\n```
1
0
[]
0
binary-tree-coloring-game
Java 100% Time 100% Memory
java-100-time-100-memory-by-peterpei666-m0f4
\nclass Solution {\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n TreeNode cur = findNode(root, x);\n int numP = 0;\n
peterpei666
NORMAL
2019-10-15T23:14:46.092027+00:00
2019-10-15T23:14:46.092063+00:00
213
false
```\nclass Solution {\n public boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n TreeNode cur = findNode(root, x);\n int numP = 0;\n if (findSize(cur.left) > n / 2) return true;\n if (findSize(cur.right) > n / 2) return true;\n if (findSize(cur) <= n / 2) return true;\n return false; \n }\n int findSize(TreeNode root) {\n if (root == null) return 0;\n return findSize(root.left) + findSize(root.right) + 1;\n }\n TreeNode findNode(TreeNode root, int x) {\n if (root == null) return null;\n if (root.val == x) {\n return root;\n } \n TreeNode left = findNode(root.left, x);\n if (left != null) return left;\n return findNode(root.right, x);\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
Easy to understand C++ 100% faster and time and space complexity
easy-to-understand-c-100-faster-and-time-huwg
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : v
pallavshah
NORMAL
2019-09-01T09:04:18.284480+00:00
2019-09-01T09:04:18.284516+00:00
189
false
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n \n void findXInTree(TreeNode*& temp, TreeNode* root, int x) {\n if(root == NULL)\n return;\n if(temp)\n return;\n if(x == root -> val)\n temp = root;\n findXInTree(temp, root -> left, x);\n findXInTree(temp, root -> right, x);\n }\n \n int count(TreeNode* root) {\n if(root == NULL)\n return 0;\n if(root -> left == NULL && root -> right == NULL)\n return 1;\n int left = count(root -> left);\n int right = count(root -> right);\n return 1 + left + right;\n }\n \n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n TreeNode* temp = NULL;\n findXInTree(temp, root, x);\n // cout << temp -> val;\n int left = count(temp -> left);\n int right = count(temp -> right);\n // cout << left << right;\n int one = max(left, right);\n if(temp -> val != root -> val)\n one = max(one, n - left - right - 1);\n return (one > (n - one));\n }\n};\n```
1
0
[]
0
binary-tree-coloring-game
C# Solution
c-solution-by-leonhard_euler-rpx8
\npublic class Solution \n{\n public bool BtreeGameWinningMove(TreeNode root, int n, int x) \n {\n var node = FindNode(root, x);\n int l = C
Leonhard_Euler
NORMAL
2019-08-05T01:26:11.503220+00:00
2019-08-05T01:26:11.503266+00:00
99
false
```\npublic class Solution \n{\n public bool BtreeGameWinningMove(TreeNode root, int n, int x) \n {\n var node = FindNode(root, x);\n int l = CountNodes(node.left), r = CountNodes(node.right);\n if(l > n/2 || r > n/2 || (n - l - r - 1) > n/2) return true;\n return false;\n }\n \n private TreeNode FindNode(TreeNode root, int val)\n {\n if(root == null || root.val == val) return root;\n var l = FindNode(root.left, val);\n if(l != null) return l;\n return FindNode(root.right, val);\n }\n \n private int CountNodes(TreeNode root)\n {\n if(root == null) return 0;\n return CountNodes(root.left) + CountNodes(root.right) + 1;\n }\n}\n```
1
0
[]
0
binary-tree-coloring-game
Python DFS Solution
python-dfs-solution-by-dragonrider-2h48
If we observe that there are three "optimal" choices for \'y\'. \'y\' could either choose \'x\'\'s parent, x\'s left child or x\'s right child. Then the final o
dragonrider
NORMAL
2019-08-04T18:46:08.183559+00:00
2019-08-04T18:46:08.183596+00:00
127
false
If we observe that there are three "optimal" choices for \'y\'. \'y\' could either choose \'x\'\'s parent, x\'s left child or x\'s right child. Then the final optimal choice for \'y\' is the optimal among those three. If any choice result wining of \'y\', then \'y\' will win. Otherwise, \'y\' will loose.\n\n\nBelow is my python implementation\n\n```python\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n \n \'\'\'\n if choose x\'s subtree, better choose the root of its larger subtree\n if choose x\'s ancestors, better choose x\'s parent.\n \'\'\'\n childcount = collections.defaultdict(int)\n leftchildren = {}\n rightchildren = {}\n parents = {}\n \n def dfs(root:TreeNode, parent:TreeNode)->int: #return a node\'s child node count including itself\n if root == None:\n return 0\n left = dfs(root.left, root)\n right = dfs(root.right, root)\n childcount[root.val] = left + right + 1\n parents[root.val] = parent\n leftchildren[root.val] = root.left\n rightchildren[root.val] = root.right\n return left + right + 1\n \n dfs(root, None)\n #case1\n if parents[x] != None:\n m = n - childcount[x]\n if m > n // 2:\n return True\n #case2\n if leftchildren[x] != None:\n m = childcount[leftchildren[x].val]\n if m > n // 2:\n return True\n #case3\n if rightchildren[x] != None:\n m = childcount[rightchildren[x].val]\n if m > n // 2:\n return True\n return False\n \n```
1
0
[]
0
painting-a-grid-with-three-different-colors
[C++/Python] DP & DFS & Bitmask - Picture explain - Clean & Concise
cpython-dp-dfs-bitmask-picture-explain-c-qhhb
Note\n- Simillar to problem: 1411. Number of Ways to Paint N \xD7 3 Grid, but in this case, the number of rows is not fixed to 3, it\'s a dynamic values <= 5. S
hiepit
NORMAL
2021-07-11T04:03:53.708578+00:00
2021-07-12T03:48:42.831678+00:00
11,193
false
**Note**\n- Simillar to problem: [1411. Number of Ways to Paint N \xD7 3 Grid](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/574912), but in this case, the number of rows is not fixed to 3, it\'s a dynamic values <= 5. So we need to use dfs to generate all possible columns.\n- Use DP to calcuate number of ways.\n- Since `M <= 5`, we can fill colors of matrix column by column. To store previous column state in DP, we can use BitMask, each 2 bits store a color (1=Red, 2=Green, 3=Blue, 0=White), so there is total 4^M column states.\n\n![image](https://assets.leetcode.com/users/images/a79897f2-eef0-4966-b551-b3b0b1cc84e8_1625980167.5595653.png)\n\n<iframe src="https://leetcode.com/playground/XwDXM7KE/shared" frameBorder="0" width="100%" height="730"></iframe>\n\n**Complexity**\n- Time: `O(N * 3^M * 2^M)`, where `N <= 1000` is number of columns, `M <= 5` is number of columns.\n\t- There is total: `N * 3^M` states in dp params, each state has up to `(2^M)` neighbors to calculate.\n\t- Why up to `2^M` neighbors each state? Because choose color of cell (0, c) has up to 2 ways *(different color from cell(0, c-1))*, choose color of cell (1, c) has up to ways *(different color from both cell(1, c-1) and cell(0, c))*... until `M` rows.\n- Space: \n\t- C++: `O(N * 4^M + 4^M * 2^M)`, because in C++ we use memory 4^M=1024 to store colors of states.\n\t- Python: `O(N * 3^M + 3^M * 2^M)`, because in Python @lru_cache up to 3^M colors of column states (red, green, blue).\n\n\n**Another version dfs neighbors in the dp function**\n<iframe src="https://leetcode.com/playground/NBz6CQzy/shared" frameBorder="0" width="100%" height="530"></iframe>
137
10
[]
21
painting-a-grid-with-three-different-colors
Top-down DP with bit mask
top-down-dp-with-bit-mask-by-votrubac-46g5
Since m is limited to 5, and colours are limited to 3, we can represent the previous column using a bit mask (two bits for each color). We can have up to 1023 c
votrubac
NORMAL
2021-07-11T04:03:02.225352+00:00
2021-07-11T18:23:38.225514+00:00
7,435
false
Since `m` is limited to `5`, and colours are limited to `3`, we can represent the previous column using a bit mask (two bits for each color). We can have up to 1023 combinations (including white color for convenience) of colors in the column.\n\n1. `cur`: colors for the current column.\n2. `prev`: colors for the previous column.\n3. when we reach the end of the column, we start a new one: `prev = cur`, and `cur = 0`.\n4. for each position, we try each color, providing it\'s not the same as the one on the `left` and `up`.\n\nTo avoid TLE, we need to memoise interim results. For simplicity, we are doing it for the entire row, not for individual cells. So, our memo dimensions are 1000 x 1023 - numbers of columns, and color combinations (bit mask) for the previous column.\n\n**C++**\n```cpp\nint dp[1001][1024] = {};\nint colorTheGrid(int m, int n, int i = 0, int j = 0, int cur = 0, int prev = 0) {\n if (i == m)\n return colorTheGrid(m, n, 0, j + 1, 0, cur);\n if (j == n)\n return 1;\n if (i == 0 && dp[j][prev])\n return dp[j][prev];\n int res = 0, up = i == 0 ? 0 : (cur >> ((i - 1) * 2)) & 3, left = prev >> (i * 2) & 3;\n for (int k = 1; k <= 3; ++k)\n if (k != left && k != up)\n res = (res + colorTheGrid(m, n, i + 1, j, cur + (k << (i * 2)), prev)) % 1000000007;\n if (i == 0)\n dp[j][prev] = res;\n return res;\n}\n```
79
4
['C']
20
painting-a-grid-with-three-different-colors
[C++] DP
c-dp-by-divyanshu1-do96
Similar to: 1411. Number of Ways to Paint N \xD7 3 Grid\n\n\n\nvector<string> moves;\nint MOD = 1e9 + 7;\nvoid fill(string s, int n, int p){\n if(n==0){\n
divyanshu1
NORMAL
2021-07-11T04:15:01.149422+00:00
2021-07-25T04:27:47.654801+00:00
4,837
false
*Similar to*: [1411. Number of Ways to Paint N \xD7 3 Grid](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/941091/c%2B%2Boror-Easy-to-understand-oror-DFS-%2B-Memorization-oror-Space-%3A-O(12n)-Time-%3AO(12n))\n\n```\n\nvector<string> moves;\nint MOD = 1e9 + 7;\nvoid fill(string s, int n, int p){\n if(n==0){\n moves.push_back(s);\n return;\n }\n for(int i=1; i<4; i++){\n if(p==i){\n continue;\n }\n string m = to_string(i);\n fill(s+m, n-1, i);\n }\n return;\n}\nclass Solution {\npublic:\n vector<vector<int>>memo;\n int solve(int n, int lastIdx, int m){\n if (n == 0) return 1;\n int ret = 0;\n if (memo[n][lastIdx] != -1) return memo[n][lastIdx];\n string last = moves[lastIdx];\n for (int idx = 0; idx<moves.size(); idx++) {\n string move = moves[idx];\n bool same = false;\n for (int i = 0; i < m; i++) if (move[i] == last[i]) same = true; \n if (!same) ret = (ret + solve(n - 1, idx, m)%MOD)%MOD;\n }\n return memo[n][lastIdx]= ret%MOD;\n }\n int colorTheGrid(int m, int n){\n moves.clear();\n fill("", m, -1);\n //cout<<moves.size()<<endl;\n memo.resize(n + 1, vector<int>(moves.size(), -1));\n int ret = 0;\n for (int idx = 0; idx < moves.size(); idx++)\n ret = (ret + solve(n-1, idx, m)%MOD)%MOD;\n return ret;\n }\n};\n\n```\n\n***UPVOTE\uD83D\uDC4D !!!***
67
11
['Dynamic Programming', 'C']
1
painting-a-grid-with-three-different-colors
Graph Based Approach | C++ | 100% Space & Time | Explained!
graph-based-approach-c-100-space-time-ex-8w1j
\t\tvector states;\n\t\tvoid generate(string state, char prev, int m){\n \n\t\t\tif(m==0){\n\t\t\t\tstates.push_back(state);\n\t\t\t\treturn;\n\t\t\t}\n\
raghavchugh21
NORMAL
2021-07-11T06:25:06.557627+00:00
2022-03-19T12:06:05.326954+00:00
2,768
false
\t\tvector<string> states;\n\t\tvoid generate(string state, char prev, int m){\n \n\t\t\tif(m==0){\n\t\t\t\tstates.push_back(state);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstring colors = "RGB";\n\t\t\tfor(auto &color: colors){\n\t\t\t\tif(color!=prev)\n\t\t\t\t\tgenerate(state+color, color, m-1);\n\t\t\t}\n\n\t\t}\n\n\t\t// We use memoization to make use of the fact that the ans only depends upon\n\t\t// the current state and the number of columns left to fill.\n\t\tint dp[250][1001];\n\t\tlong long waysToFill(int u, int cols_to_fill, vector<vector<int>> &G){\n\n\t\t\tif(cols_to_fill==0) return 1;\n\t\t\telse if(dp[u][cols_to_fill]!=-1) return dp[u][cols_to_fill];\n\n\t\t\tint ways = 0;\n\t\t\tfor(auto v: G[u]){\n\t\t\t\tways = (ways + waysToFill(v, cols_to_fill-1, G)) % M;\n\t\t\t}\n\n\t\t\treturn dp[u][cols_to_fill] = ways;\n\t\t}\n\n\t\tpublic:\n\t\tint colorTheGrid(int m, int n) {\n\t\t\n\t\t\t// ** Note that m<=5 whereas n<=1000 **\n\t\t\t// First of all we Generate all the possible color combinations (states)\n\t\t\t// for a column with size m, store them into a vector \'states\'\n\t\t\t// For Eg m=3 : RGB, BGR, RBR, GBG, ...\n\t\t\t// Also, we make sure that same colors are not adjacent (See generate function)\n\t\t\tgenerate("", \'*\', m);\n\n\t\t\t// Now, we can observe that the number of possible states (color combinations) for\n\t\t\t// current column only depend upon the previous column.\n\t\t\t// So we make a graph where there is an edge from i to j if we can transition from\n\t\t\t// state[i] to state[j] ( no same index can be of same color )\n\t\t\tint numStates = states.size();\n\t\t\tvector<vector<int>> G(numStates);\n\n\t\t\tfor(int i=0;i<numStates;i++){\n\t\t\t\tfor(int j=0;j<numStates;j++){\n\n\t\t\t\t\tbool is_compatible = true;\n\t\t\t\t\tfor(int k=0;k<m;k++){\n\t\t\t\t\t\tif(states[i][k]==states[j][k]){\n\t\t\t\t\t\t\tis_compatible = false; break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(is_compatible)\n\t\t\t\t\t\tG[i].push_back(j);\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sum up the number of ways to make a path of length n, starting from each state (node)\n\t\t\tmemset(dp, -1, sizeof(dp));\n\t\t\tint totalWays = 0;\n\t\t\tfor(int i=0;i<numStates;i++){\n\t\t\t\ttotalWays = (totalWays + waysToFill(i, n-1, G)) % M;\n\t\t\t}\n\n\t\t\treturn totalWays;\n\n\t\t}
45
0
[]
10
painting-a-grid-with-three-different-colors
[Python] O(2^m*n*m) dp solution, explained
python-o2mnm-dp-solution-explained-by-db-adxg
Solution 1\nThe idea is to go row by row and check that we do not have conflicts of colors in each row and between rows.\n\n1. C is all candidates for row, that
dbabichev
NORMAL
2021-07-11T10:11:35.243245+00:00
2021-07-12T09:40:37.740460+00:00
2,244
false
#### Solution 1\nThe idea is to go row by row and check that we do not have conflicts of colors in each row and between rows.\n\n1. `C` is all candidates for row, that is all rows, such that we do not have conflicts among horizontal adjacent cells.\n2. Also create dictionarly `d`: where for each candidate we collect all possible options for the next line such that we do not have vertical conflicts.\n3. Finally, we go level by level and for each `c1` among candidates and then for each `c2 in d[c1]`, we update number of options for `dp2[c2]`. In the end of iteration we update `dp = dp2`.\n\n#### Complexity\nWe have `O(3^m * m)` complexity to generate `C`. In fact we will have `3*2^(m-1)` options for each row. Then when we check all pairs we do `O(9^2^(2m-2) * m) = O(4^m * m)` ways. Then we have `O(4^m * m)` complexity for each level, so total time complexity is `O(4^m * n * m)`. Space complexity is `O(4^m)`.\n\n#### Code\n```python\nclass Solution:\n def colorTheGrid(self, m, n):\n C = [c for c in product([0,1,2], repeat = m) if all(x!=y for x,y in zip(c, c[1:]))]\n\n MOD, dp, d = 10**9 + 7, Counter(C), defaultdict(list)\n\n for c1, c2 in product(C, C):\n if all(x != y for x, y in zip(c1, c2)):\n d[c1].append(c2)\n\n for _ in range(n-1):\n dp2 = Counter()\n for c1 in C:\n for c2 in d[c1]:\n dp2[c2] = (dp2[c2] + dp[c1]) % MOD\n dp = dp2\n\n return sum(dp.values()) % MOD\n```\n\n#### Solution 2\n\nActually, there is solution with better complexity! The idea is Problem **1659. Maximize Grid Happiness** , you can find more explanations here: https://leetcode.com/problems/maximize-grid-happiness/discuss/936467/Python-Short-and-clean-dp-with-diagram-expained\n\n![image](https://assets.leetcode.com/users/images/95ef3564-fcd2-4f0e-901c-03cc140172d0_1626014693.972445.png)\n\nWe use so-called dp with broken profile, and on each step we try to add one more element, checking two neigbours. \n\n#### Complexity: \nWe have `mn` states for `index` and `O(2^m)` states for `row`. So, we have in total `O(2^m * m * n)` states, which of them have length `O(m)`. So, total space and time complexity here is `O(2^m * m^2*n)`\n\n#### Code 1\n```python\nclass Solution:\n def colorTheGrid(self, m, n):\n \n @lru_cache(None)\n def dp(index, row):\n if index == -1: return 1\n \n R, C = divmod(index, m)\n \n ans, allowed = 0, {0, 1, 2}\n \n if C < m - 1: allowed.discard(row[0])\n if R < n - 1: allowed.discard(row[-1])\n \n for val in allowed:\n ans += dp(index-1, (val,) + row[:-1])\n \n return ans % MOD\n \n MOD = 10**9 + 7\n return dp(m*n-1, tuple([3]*m)) % MOD\n```\n\nComplexity can be reduced to just `O(2^m * n * m)` if we use bitmasks instead of tuples: `00`, `01`, `10`, `11` represents `0, 1, 2, 3`, and we spend two bits for each of `m` element of row, so we keep number with `2m` bits. Because of `lru_cache` we use here we have quite big armotization constant, so to make it really fast you can use classical table dp.\n\n**Update** Actually, number of states is approximately `O(2^m * n * m * 2.25)`, because our row consist of two parts, each of which can start from any color and then we can take always no more than `2` options.\n\n#### Code 2\n```python\nclass Solution:\n def colorTheGrid(self, m, n):\n @lru_cache(None)\n def dp(index, row):\n if index == -1: return 1\n \n R, C = divmod(index, m)\n \n ans, allowed = 0, {0, 1, 2}\n \n if C < m - 1: allowed.discard(row >> (2*m-2))\n if R < n - 1: allowed.discard(row & 3)\n \n for val in allowed:\n ans += dp(index-1, (row >> 2) + (val<<(2*m-2)))\n \n return ans % MOD\n \n MOD = 10**9 + 7\n return dp(m*n-1, (1<<(2*m)) - 1) % MOD\n```\n\nActually we can implement the same logic without recursion, and I thought that it will make code several times faster, but no it is not. I need to inverstigate why, does anybody have any ideas? One theory is that `m` is quite small here, and because of hidden constants are quite big, we can not bead the first method.\n\n#### Code 3\n```python\nclass Solution:\n def colorTheGrid(self, m, n):\n dp, MOD = {(1<<(2*m)) - 1: 1}, 10**9 + 7\n \n for index in range(m*n-1, -1, -1):\n dp2 = Counter()\n R, C = divmod(index, m)\n \n for row in dp:\n allowed = {0, 1, 2}\n if C < m - 1: allowed.discard(row >> (2*m-2))\n if R < n - 1: allowed.discard(row & 3)\n\n for val in allowed:\n row2 = (row >> 2) + (val<<(2*m-2))\n dp2[row2] = (dp2[row2] + dp[row]) % MOD \n \n dp = dp2\n \n return sum(dp.values()) % MOD\n```\n\n**Update** as it happen, indeed when we increase `m` with fixed `n = 1000` and we an fell difference starging from `m = 10`.\n\n| m | Solution 1 time | Solution 2 time |\n|----|-----------------|-----------------|\n| 1 | 0.007 | 0.016 |\n| 2 | 0.015 | 0.041 |\n| 3 | 0.032 | 0.130 |\n| 4 | 0.094 | 0.327 |\n| 5 | 0.290 | 0.847 |\n| 6 | 0.859 | 2.006 |\n| 7 | 2.612 | 4.638 |\n| 8 | 7.965 | 10.73 |\n| 9 | 24.51 | 24.21 |\n| 10 | 75.61 | 56.07 |\n| 11 | 235.0 | 125.2 |\n| 12 | 730.2 | 279.6 |\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
42
1
['Dynamic Programming']
4
painting-a-grid-with-three-different-colors
dp state compression, very similar to 1411
dp-state-compression-very-similar-to-141-hlk3
State compression;\n\nThis questions is very similar to the 1411\tNumber of Ways to Paint N \xD7 3 Grid .\n\n1, First we rotate the grid 90 degree clockwise,
deepli
NORMAL
2021-07-11T04:04:47.049761+00:00
2021-07-11T18:20:55.664485+00:00
2,463
false
State compression;\n\nThis questions is very similar to the 1411\tNumber of Ways to Paint N \xD7 3 Grid .\n\n1, First we rotate the grid 90 degree clockwise, now it became the harder version of 1411, that is N X M Grid (M is in the range [1-5])\n2, we use a 3-based number to represent the state of one row. For example, 210 = 2 * 3^2 + 1 * 3^1 + 0 * 3^0. Let\u2019s assume 0- red, 1-blue, 2-green.\n3, selfOK() is used to check whether one row is valid or not\n4, crossOK() is used to check the adjacent two rows.\n\n\n\n```\n \n int m ;\n public int colorTheGrid(int M, int n) {\n m = M;\n \n int mod = (int)(1e9 + 7);\n \n int x = (int)Math.pow(3, m);\n int[][] dp = new int[n][x]; // dp[i][j] means the number of ways to color the grid when the i_th row is state j\n \n boolean[] f = new boolean[x]; // There are at most x = 3^m states\n boolean[][] A= new boolean[x][x]; // Chceck the adjacent two rows. For example, the fist row is state p, the second row is state q\n\t\t\n\t\t\n // preprocess all 3^m states;\n for(int i = 0; i < x; i++){\n if(selfOK(i)){\n f[i] = true;\n }\n }\n \n\t\t\n\t\t// preprocess all adjacent two rows\n for(int i = 0; i < x; i++){\n for(int j = 0; j < x; j++){\n if(f[i]&& f[j] && crossOK(i, j)){\n A[i][j] = true;\n }\n }\n }\n \n \n \n for(int i = 0; i < x; i++){\n \n if(f[i])\n dp[0][i] = 1;\n }\n \n for(int i = 1; i < n; i++){\n \n for(int p= 0; p <x; p++){\n // if current row p is not valid, continue;\n if(!f[p]) continue;\n for(int q = 0; q < x; q++){\n // the previous row is q, if q is not valid, continue;\n if(!f[q]) continue;\n if(A[p][q]){ // if row p and row q are both valid, we update dp[i][p]\n dp[i][p] = (dp[i][p] + dp[i - 1][q])%mod;\n }\n \n }\n }\n }\n \n \n int cnt = 0;\n for(int p = 0; p <x; p++){\n cnt = (cnt + dp[n - 1][p])%mod;\n }\n return cnt;\n }\n \n \n \n \n //check one row is valid or not\n boolean selfOK(int p){\n int[] A = new int[m];\n int idx = 0;\n while(p >0){\n A[idx] = p%3;\n p /= 3;\n idx++;\n }\n \n\t\t// if two adjacent colors are the same in the same row, that is invalid\n for(int i = 0; i < m - 1; i++){\n if(A[i] == A[i +1]) return false;\n }\n \n return true;\n }\n \n // check the adjacent two rows are valid or not\n boolean crossOK(int p, int q){\n int[] A = new int[m];\n int[] B = new int[m];\n \n int idx = 0;\n while(p >0){\n A[idx] = p%3;\n p /= 3;\n idx++;\n }\n \n \n idx = 0;\n while(q >0){\n B[idx] = q%3;\n q /= 3;\n idx++;\n }\n \n\t\t// if the i_th color in the upper row is the same with the i_th color in the current row, that is invalid\n for(int i = 0; i < m; i++){\n \n if(A[i] == B[i]) return false;\n }\n \n return true;\n\n }\n```
24
3
[]
7
painting-a-grid-with-three-different-colors
Java Simple Column-by-Column DP Solution O(48^2*N)
java-simple-column-by-column-dp-solution-dv9p
For m = 5, there are at most 48 valid states for a single column so we can handle it column by column.\nWe encode the color arrangement by bit mask (3 bit for a
hdchen
NORMAL
2021-07-11T04:07:51.192665+00:00
2021-07-24T08:10:07.522852+00:00
2,282
false
For m = 5, there are at most 48 valid states for a single column so we can handle it column by column.\nWe encode the color arrangement by bit mask (3 bit for a position) and use dfs to generate the all valid states.\nThen for each column, we iterator all the states and check if it\'s still valid with the previous column.\n```\nclass Solution {\n static int mod = (int) 1e9 + 7;\n public int colorTheGrid(int m, int n) {\n Map<Integer, Long> state = new HashMap();\n dfs(state, 0, m, -1, 0);\n Set<Integer> set = new HashSet(state.keySet());\n for (int i = 1; i < n; ++i) {\n Map<Integer, Long> dp = new HashMap();\n for (int a : set) {\n for (int b : set) {\n if (0 == (a & b)) dp.put(a, (dp.getOrDefault(a, 0L) + state.get(b)) % mod);\n }\n }\n state = dp;\n }\n long res = 0L;\n for (long val : state.values()) res = (res + val) % mod;\n return (int) res;\n }\n private void dfs(Map<Integer, Long> state, int j, int m, int prev, int cur) {\n if (j == m) {\n state.put(cur, state.getOrDefault(cur, 0L) + 1);\n return;\n }\n for (int i = 0; i < 3; ++i) {\n if (i == prev) continue;\n dfs(state, j + 1, m, i, (cur << 3) | (1 << i));\n }\n }\n}\n```
15
0
[]
5
painting-a-grid-with-three-different-colors
[Python] Straight forward solution
python-straight-forward-solution-by-vbsh-o75f
Using dp. Consider each row to be a state, we can find the valid adjacent states. Becomes number of paths problem.\nTime complexity : O(n*3^m) \n```\n\nfrom fun
vbshubham
NORMAL
2021-07-11T04:04:59.968236+00:00
2021-07-11T13:44:06.304760+00:00
1,515
false
Using dp. Consider each row to be a state, we can find the valid adjacent states. Becomes number of paths problem.\nTime complexity : O(n*3^m) \n```\n\nfrom functools import cache, lru_cache\nfrom itertools import product\n\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n mod = 10 ** 9 + 7\n\n def check(pos):\n return all(a != b for a, b in zip(pos, pos[1:]))\n\n def neighs(pos1, pos2):\n return all(a != b for a, b in zip(pos1, pos2))\n\n states = {\'\'.join(pos) for pos in product(\'RGB\', repeat=m) if check(pos)}\n adj = {}\n for state in states:\n adj[state] = [next_state for next_state in states if neighs(state, next_state)]\n\n @cache\n def f(prv_state, N):\n if N == 0:\n return 1\n return sum(f(next_state, N - 1) for next_state in adj[prv_state]) % mod\n\n return sum(f(state, n - 1) for state in states) % mod\n\n\n
14
2
['Dynamic Programming', 'Depth-First Search', 'Python']
1
painting-a-grid-with-three-different-colors
Thought Process, 3^(mn)mn -> n((2^(m-2))^2), 95% ever
thought-process-3mnmn-n2m-22-95-ever-by-iqycv
foreword: I\'m trying to share logical thought process for deriving various solutions from scratch with minimum tricks, if you think this style helps, please ki
jimhorng
NORMAL
2021-08-03T11:54:29.097884+00:00
2021-09-02T14:57:38.466097+00:00
938
false
*foreword: I\'m trying to share logical thought process for deriving various solutions from scratch with minimum tricks, if you think this style helps, please kindly **upvote** and/or **comment** for encouragement, or leave your thoughts to tune the content, thanks and happy thought processing :)*\n\n1) naive: find all [color choices] of [all cells] and check if meet constraint -> each cell has 3 color choices, there are m*n cells, so total ways are: `3*3*...*3` with `m*n` terms \n\t- -> Time: `O(3^(m*n) * (m*n))`\n\n2) is there any processed info can be reused? \n -> row=i ways only depends on row=i-1 ways if all ways before are embedded into row=i-1 \n```\nrow colors\ni-3 *** ***\ni-2 *** ***\ni-1 GRG GBR\ni RGB RGB\n```\n\n3) each row way as a state, each row=i state has possible transitions from all row=i-1\'s states, and filtered by constraint (color of adjacent cell differs), so state transition per row is:\n n_ways(row=i, state=way1) = valid(n_ways(row=i-1, state=way1)) + valid(n_ways(row=i-1, state=way2)) + ...\n n_ways(row=i, state=way2) = valid(n_ways(row=i-1, state=way1)) + valid(n_ways(row=i-1, state=way2)) + ...\n ...\n the number of state transitions are: `[number of row=i\'s states] * [number of row=i-1\'s states]`\n \n4) base on 3). each row has 3^m or 3^n states, since m is much smaller, so we choose m as column and states per row will be 3^m . so \n\t- [number of state transitions] = [number of row=i\'s states] * [number of row=i-1\'s states] = (3^m) * (3^m) = (3^m)^2\n\t- -> Total Time: [number of rows] * [state transitions] = `n * ( (3^m)^2 )`\n\t- -> `n * 243^2 (m=5)`\n\t since row and column are exchange-able logically in this case.\n\n5) we found that not all states are valid due to the constraint, e.g. RRB, GGB is invalid, so we can prune row\'s state as [3 choose 1, 2 choose 1, ... , 2 choose 1] , then number of states will become 3 * ( 2 ^ (m-1) ) \n\t- -> [state transitions]: ( 3 * ( 2 ^ (m-1) ) ) ^ 2\n\t- -> Total Time: `n*((3*(2^(m-1)))^2)`\n\t- -> `n * ( 48^2 )` (m=5)\n\n6) observe 5)\'s states to see if there are any repeated patterns for reducing calculations\n```\n123\n---\nRGB\nRBG\nGRB\nGBR\nBRG\nBGR\n```\n - when m=3, RGB, BGR, GRB seems the same pattern where 1st, 2nd, 3rd cell colors differs to each other, can be denoted as [123]. While RGR, GRG seems the same pattern where 1st, 3rd cell color are the same, denoted [121]. So that if we can prove each permutation of the same pattern has the same state transition, then we can safely calculate 1 permutation\'s state value(ways) and multiply by number of permutations to get total original ways.\n The permutations of a pattern [123] can be calculated by replacing as color permutations\n denoted as `P(|colors|, |pattern colors|)`, \nP(3,3)=6, when m >= 3\nP(3,2)=6, when m = 2\nP(3,1)=3, when m <= 1\n-> generalized as `P(3, min(3, m))`\n\n7) what about number of state transitions of each permutation of a specific pattern? we found numbers are the same as well, since they are also permutations of same pattern state transitions, \ne.g. m=3,\n```\nrow=i row=i-1\nBGR(123) GBG(121) GRB(123) GRG(121) RBG(123) \nBRG(123) GBR(123) RBR(121) RGB(123) RGR(121) \n```\n- n_ways(row=i, state=[123]) = n_ways(row=i-1, state=[121])*2 + n_ways(row=i-1, state=[123])*2\n\n\n8) based on 6), number of pattern as state can be: when m=3, first 2 cells as [12], then 3rd cell can choose from {1,3} and result in [123], [121] \n -> total number is 2 \n -> generalize as `1* 1 * 2^(m-2)` = `2^(m-2)`\n\n9) based on 7), since we know row=i-1\'s number of pattern as state are also 2^(m-2), how do we find all state transitions as \n `n_ways(row=i, state=way1) = n_ways(row=i-1, state=way1)*n1 + n_ways(row=i-1, state=way2)*n2 + ...`?\n ```\nrow=i row=i-1\n123 212(121) 231(123) 232(121) 312(123) \n121 212(121) 213(123) 232(121) 312(123) 313(121)\n```\n- if we think from single row=i\'s pattern [123]\'s transitions from row=i-1 possible patterns [212], [232] can also generalized to [121], which means it has [121] * 2 transitions\n\t- "normalize" row=i-1 pattern as 1st cell as 1, 2nd cell as 2, rest cell as 3 (e.g. [231] -> 2:1, 3:2, 1:3 -> pattern:[123])\n\t- finally, we can get\n\t `n_ways(row=i, state=[123]) = n_ways(row=i-1, state=[121])*2 + n_ways(row=i-1, state=[123])*2`\n\n10) base 8), 9), \n\t- -> [state transitions]: `( 2^(m-2) ) ^ 2`\n\t- -> Total Time: `n*((2^(m-2))^2)`\n\t- -> `n * ( 8^2 )` (m=5)\n\n11) we can store row\'s state transitions function in advance, so for each row\'s state-value calculation we just reference that without re-calculation of state transitions\n\n12) since each state\'s element is m <= 5, additional compression by 3-base or 2-bit doesn\'t help much\n\n< code >\n```python\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n from functools import reduce\n MOD = 10**9 + 7\n sum_mod = lambda x,y: (x+y)%MOD\n \n def normalize(pat_var):\n mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n return tuple([ mapping[e] for e in pat_var])\n \n def get_pats(m, i, pat, pats):\n if i == m-1:\n pats.append(tuple(pat))\n return\n i_nx = i+1\n for p_it_nx in (1,2,3):\n if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n pat.append(p_it_nx)\n get_pats(m, i_nx, pat, pats)\n pat.pop()\n return pats\n \n def get_trans(pat, i, pat_pre, trans):\n if i == len(pat)-1:\n pat_nl = normalize(pat_pre)\n trans[pat_nl] = trans.get(pat_nl, 0) + 1\n return\n for p_it_pre in (1,2,3):\n i_nx = i+1\n if (p_it_pre != pat[i_nx]\n and (not pat_pre or p_it_pre != pat_pre[-1])):\n pat_pre.append(p_it_pre)\n get_trans(pat, i_nx, pat_pre, trans)\n pat_pre.pop()\n return trans\n\n pats = get_pats(m, -1, [], [])\n # {pattern_i: {pattern_pre:count}}\n pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } \n \n p_counts = { pat:1 for pat in pat_trans.keys() }\n for i in range(n-1):\n p_counts_new = {}\n for pat, trans in pat_trans.items():\n p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n p_counts = p_counts_new\n \n res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n return (res * perms) % MOD\n```\n\n< reference >\n- https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/574943/Java-Detailed-Explanation-with-Graph-Demo-DP-Easy-Understand
11
0
['Dynamic Programming', 'Python']
1
painting-a-grid-with-three-different-colors
C++ Solution Using Binary Exponentiation On Matrix O(n^3 * log(m))
c-solution-using-binary-exponentiation-o-foxs
First we generate valid sequences with length N (N <= 5) (no adjacent cells have same color, ex:[1, 2, 3, 1, 3])\nWith the sequences, we can build an adjacency
felixhuang07
NORMAL
2021-07-11T04:00:37.345350+00:00
2022-04-30T05:02:47.372935+00:00
1,654
false
First we generate valid sequences with length N (N <= 5) (no adjacent cells have same color, ex:[1, 2, 3, 1, 3])\nWith the sequences, we can build an adjacency matrix.\nFor example, [1, 2, 3, 2, 1] can move to [2, 1, 2, 1, 3] because\n[1, 2, 3, 2, 1]\n[2, 1, 2, 1, 3]\nno adjacent cells have the same color\n[1, 3, 2, 1, 3] cannot move to [3, 1, 2, 1, 3] because\n[1, 3, **2**, 1, 3]\n[3, 1, **2**, 1, 3]\nWe can calculate the possible ways of length M with the adjacency matrix using the technique "Binary Exponentiation".\nTime Complexity : O(N^3 * log(M)) \n(Solvable with M <= 10^18)\n```\nconst int mod = 1e9 + 7;\n\ntypedef uint64_t ull;\n\nstruct Matrix {\n vector<vector<ull>> M;\n int N;\n Matrix(int n) {\n N = n;\n M = vector<vector<ull>>(n, vector<ull>(n));\n }\n Matrix operator*(const Matrix& other) { //overload matrix multiplication with mod\n Matrix ans(N);\n for(int i = 0; i < N; ++i)\n for(int j = 0; j < N; ++j)\n for(int k = 0; k < N; ++k)\n ans.M[i][k] = (ans.M[i][k] + M[i][j] * other.M[j][k]) % mod;\n return ans;\n }\n};\n\nMatrix FastPower(Matrix a, ull b) { //fast matrix exponentiation\n Matrix ans(a.N);\n for(int i = 0; i < a.N; ++i)\n ans.M[i][i] = 1;\n while(b) {\n if(b & 1)\n ans = ans * a;\n a = a * a;\n b >>= 1;\n }\n return ans;\n}\n\nbool check(vector<int> a, vector<int> b) { //check if sequence A can move to sequence B\n for(int i = 0; i < a.size(); ++i)\n if(a[i] == b[i])\n return 0;\n return 1;\n}\n\nset<vector<int>> s; //store sequences from the below dfs\n\nvoid dfs(vector<int> v, int n) { //generate all sequences\n if(v.size() == n) {\n s.insert(v);\n return;\n }\n v.push_back(0);\n for(int i = 1; i <= 3; ++i) { //use 123 for color red green blue\n v.back() = i;\n dfs(v, n);\n }\n return;\n}\n\nclass Solution {\npublic:\n int colorTheGrid(int n, int m) { //n <= 5\n\t s.clear();\n dfs(vector<int>(0), n);\n vector<vector<int>> valid; //store valid sequences\n for(auto v : s) { //filter valid sequences\n if(v.size() != n)\n continue;\n bool ok = 1;\n for(int i = 1; i < n; ++i) {\n if(v[i - 1] == v[i]) {\n ok = 0;\n break;\n }\n }\n if(ok)\n valid.push_back(v);\n }\n Matrix A(valid.size());\n for(int i = 0; i < valid.size(); ++i) {\n for(int j = 0; j < valid.size(); ++j) {\n if(check(valid[i], valid[j])) //if sequence i can move to sequence j\n A.M[i][j] = 1; //add an edge from sequence i to j\n }\n } \n A = FastPower(A, m - 1);\n ull ans = 0;\n for(int i = 0; i < valid.size(); ++i)\n for(int j = 0; j < valid.size(); ++j)\n ans += A.M[i][j];\n return ans % mod;\n }\n};\n```\nPlease consider upvote if it helps ^^
11
1
['C', 'Matrix']
1
painting-a-grid-with-three-different-colors
Python 3 || Linear Transformations || T/S: 99% / 97%
python-3-linear-transformations-ts-99-97-q405
\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int, mod = 1_000_000_007) -> int:\n\n if m == 1:\n return 3*pow(2, n-1, mod) %mod\n
Spaulding_
NORMAL
2024-08-16T05:37:19.207868+00:00
2024-08-16T05:37:19.207903+00:00
221
false
\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int, mod = 1_000_000_007) -> int:\n\n if m == 1:\n return 3*pow(2, n-1, mod) %mod\n\n if m == 2:\n return 2*pow(3, n, mod) %mod\n\n if m == 3:\n x0, x1 = 0, 3\n\n for _ in range(n):\n x0, x1 = ((3*x0 + 2*x1) %mod, \n (2*x0 + 2*x1) %mod)\n\n return (x0+x1) %mod \n\n if m == 4:\n x0, x1, x2 = 0, 2, 2\n\n for _ in range(n):\n x0, x1, x2 = ((3*x0 + 2*x1 + x2) %mod,\n (4*x0 + 4*x1 + 2*x2) %mod,\n ( x0 + x1 + 2*x2) %mod)\n\n return (x0+ x1 + x2) %mod\n\n if m == 5:\n (x0, x1, x2, x3, x4, x5, x6, x7) = (0, 0, 0, 0, 3, 0, 3, 0)\n\n for _ in range(n):\n\n (x0, x1, x2, x3, x4, x5, x6, x7) = (\n\n (3*x0 + 2*x1 + 2*x2 + x3 + x5 + 2*x6 + 2*x7) %mod,\n (2*x0 + 2*x1 + 2*x2 + x3 + x4 + x5 + x6 + x7) %mod,\n (2*x0 + 2*x1 + 2*x2 + x3 + x5 + 2*x6 + 2*x7) %mod,\n (1*x0 + 1*x1 + 1*x2 + 2*x3 + x4 + x5 + x6 + x7) %mod,\n ( + 1*x1 + + x3 + 2*x4 + x5 + x7) %mod,\n (1*x0 + 1*x1 + 1*x2 + x3 + x4 + 2*x5 + x6 + x7) %mod,\n (2*x0 + 1*x1 + 2*x2 + x3 + x5 + 2*x6 + x7) %mod,\n (2*x0 + 1*x1 + 2*x2 + x3 + x4 + x5 + x6 + 2*x7) %mod )\n\n return (x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7) %mod\n```\nhttps://leetcode.com/problems/painting-a-grid-with-three-different-colors/submissions/1357342872/\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `n`.\n\n\n\n
9
0
['Python3']
0
painting-a-grid-with-three-different-colors
Python count solution
python-count-solution-by-faceplant-fvgp
\n# find all possible patterns for a single row: [rgb, rbg, ...]\ndef findComb(s):\n\tif len(s) < m:\n\t\tfor c in "rgb":\n\t\t\tif c != s[-1]:\n\t\t\t\tfindCom
FACEPLANT
NORMAL
2021-07-11T04:03:36.441730+00:00
2021-07-11T05:14:00.754128+00:00
795
false
```\n# find all possible patterns for a single row: [rgb, rbg, ...]\ndef findComb(s):\n\tif len(s) < m:\n\t\tfor c in "rgb":\n\t\t\tif c != s[-1]:\n\t\t\t\tfindComb(s + c)\n\telse:\n\t\tks.append(s)\nks = []\nfor c in "rgb":\n\tfindComb(c)\n\n# find all possible pairs: {rgb: [gbr, brg, ...], brg: [gbr, ...]}\nh = {}\nfor k in ks:\n\th[k] = []\n\tfor v in ks:\n\t\tif all(k[i] != v[i] for i in range(m)):\n\t\t\th[k].append(v)\n\n# count row by row\nresult = {k : 1 for k in ks}\nfor _ in range(n - 1):\n\ttemp = {k : 0 for k in ks}\n\tfor k in ks:\n\t\tfor v in h[k]:\n\t\t\ttemp[k] += result[v]\n\tresult = temp\n\n# return sum\nreturn sum(result.values()) % (10 ** 9 + 7)\n```
9
0
[]
2
painting-a-grid-with-three-different-colors
[Python] Simple Top-down DP explained
python-simple-top-down-dp-explained-by-w-wz8g
As each column is at most 5 colours high, then we process them column by column. We simply try all combinations and keep processing the ones that do not share a
watashij
NORMAL
2021-11-03T01:55:50.799148+00:00
2021-11-03T01:55:50.799185+00:00
693
false
As each column is at most 5 colours high, then we process them column by column. We simply try all combinations and keep processing the ones that do not share any colour with the previous column. \n\nThe trick is to use bit mask. We can label the 3 colours as `1`, `2`, `4`, which in binary form is `001`, `010`, `100`. So when we do an and operation between two columns, we know the condition is satisfied if the and operation gives me 0. For example, column 1 has colour `001 010 100`, then column 2 can have colours `010 100 001` or `010 100 010` etc.\n\n```python\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n MOD = 10**9 + 7\n def generateColumn(prev, count): # find all possible column colour combinations\n if count == m: return [0]\n columns = []\n for colour in (1, 2, 4):\n if colour == prev: continue\n for suffix in generateColumn(colour, count + 1):\n columns.append((colour << count * 3) | suffix) # count * 3 because each colour has 3 bits\n return columns\n possibleColumns = generateColumn(0, 0) \n \n @lru_cache(None)\n def dfs(prevColumn, columnIndex):\n if columnIndex >= n: return 1\n res = 0\n for column in possibleColumns:\n if prevColumn & column: continue\n res = (res + dfs(column, columnIndex + 1)) % MOD\n return res\n return dfs(0, 0)\n```
7
0
[]
1
painting-a-grid-with-three-different-colors
💥💥 Beats 100% on runtime and memory [EXPLAINED]
beats-100-on-runtime-and-memory-explaine-wgow
Intuition\nColoring a grid such that no two adjacent cells have the same color, leveraging the limited number of colors (red, green, blue) to create valid combi
r9n
NORMAL
2024-10-20T09:36:16.251050+00:00
2024-10-20T09:36:16.251082+00:00
103
false
# Intuition\nColoring a grid such that no two adjacent cells have the same color, leveraging the limited number of colors (red, green, blue) to create valid combinations while ensuring that all cells are painted.\n\n# Approach\nGenerate all valid color combinations for a single row, build an adjacency list representing valid transitions between these combinations, and use a depth-first search (DFS) with memoization to count the number of ways to paint the grid based on the constraints.\n\n# Complexity\n- Time complexity:\nO(n\u22C53 m ), where \uD835\uDC5B n is the number of rows and \uD835\uDC5A m is the number of columns, primarily due to generating valid color combinations and the DFS traversal.\n\n- Space complexity:\nO(3m + n\u22C5k), where \uD835\uDC58 k is the number of valid combinations for a row, accounting for storing the combinations and the memoization table used in DFS.\n\n# Code\n```csharp []\npublic class Solution\n{\n private const int Mod = 1_000_000_007;\n\n private int Dfs(int n, List<List<int>> adj, int src, int[,] dp)\n {\n if (n == 0) return 1;\n if (dp[n, src] != -1) return dp[n, src];\n\n int totalWays = 0;\n foreach (var neighbor in adj[src])\n {\n totalWays = (totalWays + Dfs(n - 1, adj, neighbor, dp)) % Mod;\n }\n\n return dp[n, src] = totalWays;\n }\n\n private void GenerateValidColors(List<string> colors, int lastColor, int remaining, string current)\n {\n if (remaining == 0)\n {\n colors.Add(current);\n return;\n }\n\n for (int i = 0; i < 3; i++)\n {\n if (lastColor != i)\n {\n GenerateValidColors(colors, i, remaining - 1, current + i);\n }\n }\n }\n\n private bool AreColorsCompatible(string color1, string color2)\n {\n for (int i = 0; i < color1.Length; i++)\n {\n if (color1[i] == color2[i]) return false;\n }\n return true;\n }\n\n public int ColorTheGrid(int m, int n)\n {\n var colorCombinations = new List<string>();\n for (int i = 0; i < 3; i++)\n {\n GenerateValidColors(colorCombinations, i, m - 1, i.ToString());\n }\n\n var adj = new List<List<int>>(colorCombinations.Count);\n for (int i = 0; i < colorCombinations.Count; i++)\n {\n adj.Add(new List<int>());\n }\n\n for (int i = 0; i < adj.Count; i++)\n {\n for (int j = 0; j < adj.Count; j++)\n {\n if (AreColorsCompatible(colorCombinations[i], colorCombinations[j]))\n {\n adj[i].Add(j);\n }\n }\n }\n\n var dp = new int[n + 1, adj.Count];\n for (int i = 0; i <= n; i++)\n {\n for (int j = 0; j < adj.Count; j++)\n {\n dp[i, j] = -1;\n }\n }\n\n int totalWays = 0;\n for (int i = 0; i < colorCombinations.Count; i++)\n {\n totalWays = (totalWays + Dfs(n - 1, adj, i, dp)) % Mod;\n }\n\n return totalWays;\n }\n}\n\n```
6
0
['Dynamic Programming', 'Backtracking', 'Depth-First Search', 'C#']
0
painting-a-grid-with-three-different-colors
[EASY] Machine Learning + Web Development + Blockchain + AR/VR + Bitset DP
easy-machine-learning-web-development-bl-30mi
This problem can be easily solved using Machine Learning + Web Development + Blockchain + AR/VR + Bitset DP:\n\nclass Solution {\npublic:\n void backtrack(lo
nikhilbalwani
NORMAL
2022-01-07T17:55:22.356048+00:00
2022-01-07T17:55:22.356092+00:00
827
false
* This problem can be easily solved using Machine Learning + Web Development + Blockchain + AR/VR + Bitset DP:\n```\nclass Solution {\npublic:\n void backtrack(long curr, int m, vector<int>& states) {\n if (m == 0) {\n states.push_back(curr);\n return;\n }\n \n for (int i = 1; i < 4; ++i) {\n if (i != (curr & 0b11)) {\n backtrack((curr << 2) + i, m - 1, states);\n }\n }\n }\n \n bool is_consistent(int state1, int state2, int m) {\n \n for (int i = 0; i < m; ++i) {\n if ( (state1 & 0b11) == (state2 & 0b11) ) {\n return false;\n }\n state1 >>= 2;\n state2 >>= 2;\n }\n return true;\n }\n \n int colorTheGrid(int m, int n) {\n vector <int> states;\n int MOD = 1000000007, ans = 0;\n \n backtrack(0, m, states);\n \n unordered_map <int, vector <int>> prev;\n \n for (int state1: states) {\n for (int state2: states) {\n if (is_consistent(state1, state2, m)) {\n prev[state1].push_back(state2);\n }\n }\n }\n \n int limit = 0;\n \n for (int i = 0; i < m; ++i) {\n limit <<= 2;\n limit += 0b11;\n }\n vector <vector<int>> dp(n, vector<int>(limit + 1, 0));\n \n for (int state: states) {\n dp[0][state] = 1;\n \n if (0 == n - 1) {\n ans += dp[0][state];\n }\n }\n \n for (int i = 1; i < n; ++i) {\n for (int state: states) {\n for (int prev_state: prev[state]) {\n dp[i][state] = (dp[i][state] + dp[i - 1][prev_state]) % MOD;\n }\n \n if (i == n - 1) {\n ans = (ans + dp[i][state]) % MOD;\n }\n }\n }\n \n return ans;\n \n }\n};\n```
5
3
[]
1
painting-a-grid-with-three-different-colors
[c++] simple graph + memoization based solution with comments
c-simple-graph-memoization-based-solutio-ddtd
\nclass Solution {\npublic:\n \n vector<vector<long long int>>dp;\n vector<string>v;\n #define mod 1000000007\n \n //generating all proper str
SJ4u
NORMAL
2021-07-11T10:43:40.745022+00:00
2021-07-11T10:43:40.745057+00:00
793
false
```\nclass Solution {\npublic:\n \n vector<vector<long long int>>dp;\n vector<string>v;\n #define mod 1000000007\n \n //generating all proper strings (no adj of same color of size m )\n \n void recurs(int m,char prev,string s)\n {\n if(m==0)\n {\n v.push_back(s);\n return ;\n }\n \n string c="RGB";\n \n for(auto x:c)\n {\n if(x!=prev)\n recurs(m-1,x,s+x);\n }\n }\n \n \n long long int recurs(vector<int>graph[],int i,int n)\n {\n if(n==1)\n return 1;\n \n if(dp[i][n]!=-1)\n return dp[i][n];\n \n long long int a=0;\n \n for(auto x:graph[i])\n a+=recurs(graph,x,n-1)%mod;\n \n return dp[i][n]=a%mod;\n }\n \n int colorTheGrid(int m, int n) {\n \n //generating valid strings\n recurs(m,\'@\',"");\n \n \n // for(auto x:v)\n // cout<<x<<" ";\n \n vector<int>graph[v.size()];\n \n //graph construction\n \n for(int i=0;i<v.size();i++)\n {\n for(int j=0;j<v.size();j++)\n {\n bool flag=1;\n for(int k=0;k<m;k++)\n {\n if(v[i][k]==v[j][k])\n {\n flag=0;\n break;\n }\n }\n if(flag&&i!=j)\n {\n graph[i].push_back(j);\n }\n }\n }\n \n \n //finding all valid paths from all possible startings\n \n long long int ans=0;\n dp.resize(v.size(),vector<long long int>(n+1,-1));\n \n for(int i=0;i<v.size();i++)\n ans+=recurs(graph,i,n)%mod;\n\n return ans%mod;\n \n }\n};\n```
5
0
['Dynamic Programming', 'Graph', 'C']
2
painting-a-grid-with-three-different-colors
[Python3] DP 5 Cases
python3-dp-5-cases-by-agrpractice-yt51
DP 5 Cases\n\nInuition\n\nThere are only 5 cases to handle (1 <= m <= 5). Since m is small the recurrence relations per m can be discovered and returned.\n\nWit
AgrPractice
NORMAL
2022-12-04T22:34:16.843190+00:00
2023-01-16T19:12:32.209982+00:00
640
false
**DP 5 Cases**\n\n**Inuition**\n\nThere are only 5 cases to handle (`1 <= m <= 5`). Since `m` is small the recurrence relations per `m` can be discovered and returned.\n\nWith `m` fixed, for each time we increase `n` think in terms of possible `1*m` blocks that can be added to all existing `(n - 1)*m` blocks. \n\n**Case #1: `m == 1`**\n\nEverytime we increment `n` another block is added per existing `n - 1` block. Each 3 color block can only add 2 new blocks (different color blocks) each increment.\n\nResulting relation:\n```\na1 = 3\nan = 2*a(n-1)\n```\n\n**Case #2: `m == 2`**\n\nFrom the second example in the problem we can see that there are initially 6 `1*2` blocks. Each `1*2` block can be appended to 3 other `1*2` blocks (without causing adjacency).\n\n\nResulting relation:\n```\na1 = 6\nan = 3*a(n-1)\n```\n\n**Case #3: `m == 3`**\n\nFrom the problem example ([#1](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/description/)) in [1411. Number of Ways to Paint N \xD7 3 Grid](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/solutions/2957266/python3-recurrence-relation-to-dp-process/) (same problem but `m==3`) we can see that there are initially 12 `1*3` blocks. There are 2 possible patterns of `1*3` blocks complying with the adjacency restriction (divided into columns - seen below). Pattern `a` consists of 3 different colors. Pattern `b` consists of a single middle color and 2 matching end colors. When incrementing `n` each `1*3` block from the first group `a` can append 3 of its own kind and 2 from the second group `b` (without causing adjacency). When incrementing `n` each `1*3` block from the second group can append 2 of its own kind and 2 from the first group (without causing adjacency). One can brute force find the recurrence relation by taking an arbitrary block in the initial group `a` and visually examine how many blocks in the initial group `b` appended would not cause adjacency issues. One would do the same but for group `a` to itself (getting the `a` relation). One would then repeat the process with group `b` (getting the `b` relation).\n\n![3.png](https://assets.leetcode.com/users/images/60087f14-d316-41eb-bd77-19c4eb51b984_1670192178.682216.png)\n\nResulting relation:\n```\na1 = 6; b1 = 6\nan = 3*a(n-1) + 2*b(n-1)\nbn = 2*a(n-1) + 2*b(n-1)\n```\n\n**Case #4: `m == 4`**\n\nThe same methodology for `m == 3` can be performed for `m == 4` with the following groups after calculating the coefficients. Count from the following image:\n\n![4.png](https://assets.leetcode.com/users/images/2695f9a9-e2c3-4dd5-aa28-f14c4ecf97e0_1670191508.0438693.png)\n\nResulting relation:\n```\na1 = 6; b1 = 6; c1 = 6; d1 = 6\nan = 3*a(n-1) + b(n-1) + 2*c(n-1) + 2*d(n-1)\nbn = a(n-1) + 2*b(n-1) + c(n-1) + d(n-1)\ncn = 2*a(n-1) + b(n-1) + 2*c(n-1) + 2*d(n-1)\ndn = 2*a(n-1) + b(n-1) + 2*c(n-1) + 2*d(n-1)\n```\n\n**Case #5: `m == 5`**\n\nThe same methodology for `m == 4` can be performed for `m == 5` with the following groups:\n\n![5.png](https://assets.leetcode.com/users/images/90259f72-ce2b-48ab-8f43-7bfbda1ad72c_1670191524.0780618.png)\n\nResulting relation:\n```\na1 = 6; b1 = 6; c1 = 6; d1 = 6; e1 = 6; f1 = 6; g1 = 6; h1 = 6 \nan = 2*a(n-1) + b(n-1) + c(n-1) + d(n-1) + 2*e(n-1) + 2*f(n-1) + g(n-1) + h(n-1)\nbn = a(n-1) + 2*b(n-1) + c(n-1) + d(n-1) + g(n-1)\ncn = a(n-1) + b(n-1) + 2*c(n-1) + d(n-1) + e(n-1) + f(n-1) + g(n-1) + h(n-1)\ndn = a(n-1) + b(n-1) + c(n-1) + 2*d(n-1) + 2*e(n-1) + 2*f(n-1) + g(n-1) + h(n-1)\nen = 2*a(n-1) + c(n-1) + 2*d(n-1) + 3*e(n-1) + 2*f(n-1) + g(n-1) + 2*h(n-1)\nfn = 2*a(n-1) + c(n-1) + 2*d(n-1) + 2*e(n-1) + 2*f(n-1) + g(n-1) + 2*h(n-1)\ngn = a(n-1) + b(n-1) + c(n-1) + d(n-1) + e(n-1) + f(n-1) + 2*g(n-1) + h(n-1)\nhn = a(n-1) + c(n-1) + d(n-1) + 2*e(n-1) + 2*f(n-1) + g(n-1) + 2*h(n-1)\n```\n\n**Code**\n```Python3 []\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \'\'\'\n Solves a given recurrence relation\n @params dp: the nth sum per ith equation\n @params coeff: coefficients for the ith equation\n \'\'\'\n def solve_rel(dp, coeff):\n for _ in range(n - 1):\n for i in range(len(dp)):\n tmp = 0\n for j, c in enumerate(coeff[i]):\n # If j >= i we must add the second last\n #value appended, we already updated that dp.\n tmp += c*dp[j][-1 if j >= i else -2]\n dp[i].append(tmp)\n\n return sum(e[-1] for e in dp) % 1000000007\n\n\n if m == 1:\n return solve_rel([[3]], [[2]])\n if m == 2:\n return solve_rel([[6]], [[3]])\n elif m == 3:\n return solve_rel([[6], [6]], [[3,2], [2,2]])\n elif m == 4:\n return solve_rel(\n [[6], [6], [6], [6]], \n [[3,1,2,2], [1,2,1,1], [2,1,2,2], [2,1,2,2]])\n else:\n return solve_rel(\n [[6], [6], [6], [6], [6], [6], [6], [6]],\n [\n [2,1,1,1,2,2,1,1], \n [1,2,1,1,0,0,1,0], \n [1,1,2,1,1,1,1,1], \n [1,1,1,2,2,2,1,1], \n [2,0,1,2,3,2,1,2], \n [2,0,1,2,2,2,1,2], \n [1,1,1,1,1,1,2,1], \n [1,0,1,1,2,2,1,2]\n ])\n```
4
0
['Dynamic Programming', 'Python', 'Python3']
0
painting-a-grid-with-three-different-colors
Java Solution with Fast matrix power
java-solution-with-fast-matrix-power-by-54z2t
1. Group possible paintings of a row to their templates and find number of painting of each template.\n#2. Find for each template pair how many paintings of sec
rs9
NORMAL
2021-07-11T18:35:54.562949+00:00
2021-07-11T18:58:35.355809+00:00
1,112
false
#1. Group possible paintings of a row to their templates and find number of painting of each template.\n#2. Find for each template pair how many paintings of second template can be after each painting of first template.\n#3. create vector A with number of possible paintings of one row for each template (as said in #1).\n#4. create matrix B from number from #2\n#5. calculate A*B^(n-1)\n#6. Calculate sum of elements in #5\n\nCompelxity of multiplying:\nnumber of rows in matrix N= 2^(m-2)\none multiplication takes - O(N^3)\nnumber of multiplication - O(logN)\n\nTotal complexity - O(8^m * logN), or can be considered as O(logN) as m is very strictly limited and both A and B can be computed ahead-of-time.\n\n#Update\nNumber of painting for each template is 6, and solution can be simplified.\n\n```\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Solution {\n public static final int p = 1_000_000_007;\n\n public int colorTheGrid(int m, int n) {\n if (m == 1) return (int) (3L * powMod(2, n - 1) % p);\n if (m == 2) return (int) (6L * powMod(3, n - 1) % p);\n if (n == 1) return (int) (3L * powMod(2, m - 1) % p);\n if (n == 2) return (int) (6L * powMod(3, m - 1) % p);\n\n int totalTemplates = 1 << (m - 2);\n int totalPaintings = binPow(3, m);\n\n int[] paintingToTemplate = new int[totalPaintings];\n long[] paintingCountForTemplate = new long[totalTemplates];\n long[][] templateEdgeCount = new long[totalTemplates][totalTemplates];\n\n Map<Integer, Integer> templateToIndex = new HashMap<>(1 << (m - 2));\n\n int templateCounter = 0;\n for (int i = 0; i < totalPaintings; i++) {\n int type = getType(i, m);\n if (type == -1) {\n paintingToTemplate[i] = -1;\n continue;\n }\n Integer templateIndex = templateToIndex.get(type);\n if (templateIndex == null) {\n templateToIndex.put(type, templateCounter);\n templateIndex = templateCounter++;\n }\n paintingToTemplate[i] = templateIndex;\n paintingCountForTemplate[templateIndex]++;\n }\n for (int i = 0; i < totalPaintings; i++) {\n if (paintingToTemplate[i] == -1) continue;\n for (int j = i + 1; j < totalPaintings; j++) {\n if (paintingToTemplate[j] == -1) continue;\n if (checkAllowance(i, j, m)) {\n templateEdgeCount[paintingToTemplate[i]][paintingToTemplate[j]]++;\n templateEdgeCount[paintingToTemplate[j]][paintingToTemplate[i]]++;\n }\n }\n }\n for (int i = 0; i < totalTemplates; i++) {\n long c = paintingCountForTemplate[i];\n for (int j = 0; j < totalTemplates; j++) {\n templateEdgeCount[i][j] /= c;\n }\n }\n\n long[][] matrixPower = matrixPower(templateEdgeCount, n - 1);\n long ans = 0;\n for (int i = 0; i < totalTemplates; i++) {\n long s = 0;\n long[] arr = matrixPower[i];\n for (long a : arr) s += a;\n ans += paintingCountForTemplate[i] * s;\n }\n return (int) (ans % p);\n }\n\n private static boolean checkAllowance(int a, int b, int m) {\n for (int i = 0; i < m; i++) {\n if (a % 3 == b % 3) return false;\n a /= 3;\n b /= 3;\n }\n return true;\n }\n\n private static int getType(int a, int m) {\n int[] digits = new int[3];\n int first = a % 3;\n int second = a % 9 / 3;\n if (first == second) return -1;\n digits[second] = 1;\n digits[3 - first - second] = 2;\n int prev = second;\n int type = 1;\n m -= 2;\n a /= 9;\n while (m-- > 0) {\n int curr = a % 3;\n if (prev == curr) return -1;\n type = type * 3 + digits[curr];\n prev = curr;\n a /= 3;\n }\n return type;\n }\n\n private static int powMod(int a, int b) {\n long res = 1;\n while (b != 0)\n if ((b & 1) != 0) {\n res = (res * a) % p;\n --b;\n } else {\n a = (int) (((long) a * a) % p);\n b >>= 1;\n }\n return (int) res;\n }\n\n private static int binPow(int a, int n) {\n int res = 1;\n int tmp = a;\n while (n != 0) {\n if ((n & 1) != 0)\n res *= tmp;\n tmp *= tmp;\n n >>= 1;\n }\n return res;\n }\n\n private static long[][] matrixPower(long[][] base, long pow) {\n int n = base.length;\n long[][] res = new long[n][n];\n for (int i = 0; i < n; i++) {\n res[i][i] = 1;\n }\n while (pow != 0) {\n if ((pow & 1) != 0) {\n res = multiplyMatrix(res, base);\n --pow;\n } else {\n base = multiplyMatrix(base, base);\n pow >>= 1;\n }\n }\n return res;\n }\n\n private static long[][] multiplyMatrix(long[][] a, long[][] b) {\n int n = a.length;\n long[][] ans = new long[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n for (int k = 0; k < n; k++) {\n ans[i][j] += a[i][k] * b[k][j];\n }\n ans[i][j] %= p;\n }\n }\n return ans;\n }\n}\n\n```
4
0
['Dynamic Programming', 'Java']
0
painting-a-grid-with-three-different-colors
Same as N*3 colors c++ best easy soln
same-as-n3-colors-c-best-easy-soln-by-_r-apa4
```\n//just do n*3 and generalise case for 1,2,3,4,5 copy \nint dp[5000][5][5][5][5][5];\nclass Solution {\npublic:\n int mod=1000000007;\n \n bool ch
_rampj
NORMAL
2021-07-11T04:04:25.420661+00:00
2023-12-06T18:55:39.067863+00:00
454
false
```\n//just do n*3 and generalise case for 1,2,3,4,5 copy \nint dp[5000][5][5][5][5][5];\nclass Solution {\npublic:\n int mod=1000000007;\n \n bool check(int a, int b, int c,int d,int e, int na, int nb, int nc,int nd,int ne){\n if(na!=a && nb!=b &nc!=c && nd!=d && ne!=e && na!=nb && nb!=nc && nc!=nd && nd!=ne)return true;\n return false;\n }\n \n \n \n int sol(int i, int n, int a, int b, int c,int d,int e){\n if(i==n)return 1;\n if(dp[i][a+1][b+1][c+1][d+1][e+1]!=-1)return dp[i][a+1][b+1][c+1][d+1][e+1];\n int ans=0;\n for(int na=0;na<3;na++){\n for(int nb=0;nb<3;nb++){\n for(int nc=0;nc<3;nc++){\n for(int nd=0;nd<3;nd++){\n for(int ne=0;ne<3;ne++){\n if(!check(a,b,c,d,e,na,nb,nc,nd,ne))continue;\n ans=(ans+sol(i+1,n,na,nb,nc,nd,ne))%mod;\n }\n }\n }\n }\n }\n return dp[i][a+1][b+1][c+1][d+1][e+1]=ans;\n }\n \n \n \n bool check(int a, int b, int c,int d, int na, int nb, int nc,int nd){\n if(na!=a && nb!=b &nc!=c && nd!=d && na!=nb && nb!=nc && nc!=nd )return true;\n return false;\n }\n \n \n \n int sol(int i, int n, int a, int b, int c,int d){\n if(i==n)return 1;\n if(dp[i][a+1][b+1][c+1][d+1][0]!=-1)return dp[i][a+1][b+1][c+1][d+1][0];\n int ans=0;\n for(int na=0;na<3;na++){\n for(int nb=0;nb<3;nb++){\n for(int nc=0;nc<3;nc++){\n for(int nd=0;nd<3;nd++){\n {\n if(!check(a,b,c,d,na,nb,nc,nd))continue;\n ans=(ans+sol(i+1,n,na,nb,nc,nd))%mod;\n }\n }\n }\n }\n }\n return dp[i][a+1][b+1][c+1][d+1][0]=ans;\n }\n bool check(int a, int b, int c, int na, int nb, int nc){\n if(na!=a && nb!=b &nc!=c && na!=nb & nb!=nc)return true;\n return false;\n }\n //int dp[5000][4][4][4]; // it should be [3][3][3] nut since we have given in sol fuction so for the +1 thing we are taking one more\n int sol(int i, int n, int a, int b, int c){\n if(i==n)return 1;\n if(dp[i][a+1][b+1][c+1][0][0]!=-1)return dp[i][a+1][b+1][c+1][0][0];\n int ans=0;\n for(int na=0;na<3;na++){\n for(int nb=0;nb<3;nb++){\n for(int nc=0;nc<3;nc++){\n if(!check(a,b,c,na,nb,nc))continue;\n ans=(ans+sol(i+1,n,na,nb,nc))%mod;\n }\n }\n }\n return dp[i][a+1][b+1][c+1][0][0]=ans;\n }\n \n bool check(int a, int b, int na, int nb){\n if(na!=a && nb!=b && na!=nb )return true;\n return false;\n }\n //int dp[5000][4][4][4]; // it should be [3][3][3] nut since we have given in sol fuction so for the +1 thing we are taking one more\n int sol(int i, int n, int a, int b){\n if(i==n)return 1;\n if(dp[i][a+1][b+1][0][0][0]!=-1)return dp[i][a+1][b+1][0][0][0];\n int ans=0;\n for(int na=0;na<3;na++){\n for(int nb=0;nb<3;nb++){\n {\n if(!check(a,b,na,nb))continue;\n ans=(ans+sol(i+1,n,na,nb))%mod;\n }\n }\n }\n return dp[i][a+1][b+1][0][0][0]=ans;\n }\n \n bool check(int a, int na){\n if(na!=a)return true;\n return false;\n }\n //int dp[5000][4][4][4]; // it should be [3][3][3] nut since we have given in sol fuction so for the +1 thing we are taking one more\n int sol(int i, int n, int a){\n if(i==n)return 1;\n if(dp[i][a+1][0][0][0][0]!=-1)return dp[i][a+1][0][0][0][0];\n int ans=0;\n for(int na=0;na<3;na++){\n \n {\n if(!check(a,na))continue;\n ans=(ans+sol(i+1,n,na))%mod;\n }\n }\n return dp[i][a+1][0][0][0][0]=ans;\n }\n \n int colorTheGrid(int n, int m) {\n memset(dp,-1,sizeof (dp));\n if (n==5)\n return sol(0,m,-1,-1,-1,-1,-1);\n if (n==4)\n return sol(0,m,-1,-1,-1,-1);\n if (n==3)\n return sol(0,m,-1,-1,-1);\n if (n==2)\n return sol(0,m,-1,-1);\n if (n==1)\n return sol(0,m,-1);\n return 0;\n } \n};
4
6
['C++']
2
painting-a-grid-with-three-different-colors
O(9*(n+m)*4^{m-1}): Backtracking + dynamic programming
o9nm4m-1-backtracking-dynamic-programmin-j8ko
We have m rows and n columns; we need to determine how many colorings of the grid exist where no two 4-directionally adjacent cells have the same color.\n\nGENE
shaunakdas88
NORMAL
2022-07-11T18:26:28.149505+00:00
2022-07-12T14:31:08.615689+00:00
292
false
We have `m` rows and `n` columns; we need to determine how many colorings of the grid exist where no two 4-directionally adjacent cells have the same color.\n\n**GENERATING VALID COLUMNS: BACKTRACKING**\nWe first generate the set of all possible "valid columns", i.e. any column where no two consecutive rows are the same color. A column will consist of `m <= 5` cells, so we have:\n- 3 choices for the top cell\n- 2 choices for the remaining cells (any color except that of the cell on top of it)\n\nSo we are talking about `k = 3 * 2^{m-1}` possible columns to generate. This can be easily accomplished through backtracking, so we leave that to the reader. Denote this set `Valid` moving forward.\n\n**PARTITIONING SAMPLE SPACE: RECURRENCE RELATION**\nFor a matrix with precisely `i` columns of height/rows `m`, we consider the set:\n\n```\nS(i, j) = {set of matrices with i columns, where the last column corresponds to the jth valid column generated above} \n```\nwhere we enumerate the previously determined columns in `Valid` from `j=1, ... 3 * 2^{m-1} =: k`.\n\nThe set of `m-by-i` matrices where we don\'t have adjacent cells with same color is partitioned by `S(i, 1), ..., S(i, k)`. Therefore, we get our final result for an `m-by-n` matrix will be:\n```\n|S(n, 1)| + ... + |S(n, k)|\n```\nSo we can focus on the local problem of computing the size of each `S(i, j)`, and then add these together to get our final result.\n\nIf the last/`i`th column corresponds to valid column `j` (`j = 1, ..., k`), then we know that the only restriction we have is that the `i-1`st column needs to be one which did not have a row with the same color as the corresponding row in `j`; so we get:\n```\n|S(i, j)| = sum_{v in Valid: v and j do not have a common colored row} |S(i - 1, v)| \n```\nThus, we have our recurrence relation, to build to our final solution.\n\n**PRECOMPUTING**\nTo avoid computing whether a pair of columns in `Valid` share a row that has the same color, we precompute this pair-wise for everything in `Valid`, before our dynamic programming, to save time.\n\n\n**A NOTE ON TIME COMPLEXITY**\nWe notice that the time complexity of the above is `O((n + m) * 3^2 * 4^{m-1})`. Of course, the 3 and 2 come from the fact that we are only allowed 3 possible colors, and so `|Valid| = 3 * (3 - 1)^{m-1} = 3 * 2^{m-1}`. If there were arbitrary `c` possible colors we could use, then `|Valid| = c * (c - 1)^{m-1}` possible valid columns, and our overall time complexity becomes `O((n + m) * c^2 * (c - 1)^{2(m - 1)})`.\n\n**CODE**\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n mod = 10 ** 9 + 7\n \n # STEP 1: Generate all possible valid columns => O(m * 3 * 2^{m-1})\n valid_cols = []\n \n def backtrack(curr_col: List[int]):\n nonlocal valid_cols\n # Copy of the array is O(m)\n if len(curr_col) == m:\n valid_cols.append(curr_col.copy())\n return\n for i in range(1, 3):\n next_color = (curr_col[-1] + i) % 3\n curr_col.append(next_color)\n backtrack(curr_col)\n curr_col.pop()\n \n for color in range(3):\n backtrack([color])\n \n \n # STEP 2: Determine which columns can be adjacent to one another => O(m * 3^2 * 4^{m-1})\n k = len(valid_cols)\n valid = [[False] * k for i in range(k)]\n for i in range(k):\n for j in range(i + 1, k):\n v = True\n for row in range(m):\n if valid_cols[i][row] == valid_cols[j][row]:\n v = False\n break\n valid[i][j] = v\n valid[j][i] = v\n \n \n # STEP 3: Run dynamic programming => O(n * 3^2 * 4^{m-1})\n dp = [[0] * k for i in range(n)]\n for valid_col in range(k):\n dp[0][valid_col] = 1\n for i in range(1, n):\n for curr_valid in range(k):\n for prev_valid in range(k):\n if valid[prev_valid][curr_valid] == False:\n continue\n dp[i][curr_valid] = (dp[i][curr_valid] + dp[i - 1][prev_valid]) % mod\n \n\t\t\n\t\t# STEP 4: sum over partition of all possible valid ending columns\n res = 0\n for i in range(k):\n res = (res + dp[n - 1][i]) % mod\n return res\n```\n
3
0
[]
0
painting-a-grid-with-three-different-colors
Simple Solution with DP & Bitmask
simple-solution-with-dp-bitmask-by-faang-9vqw
Use 2bits to represent the state each cell, need 2*m bits since there are m rows\n2. Use 00, 01, 10 to represent 3 types of color\n3. Update dp[i][j] from dp[i
faang2022
NORMAL
2021-07-11T05:37:06.345421+00:00
2021-07-11T05:44:47.744610+00:00
419
false
1. Use 2bits to represent the state each cell, need 2*m bits since there are m rows\n2. Use 00, 01, 10 to represent 3 types of color\n3. Update dp[i][j] from dp[i-1][k] if j, k, and (j, k) are valid. j, k is the state of the colume\n```\nclass Solution {\npublic:\n const int M = 1e9+7;\n int m;\n \n\t// check if same row has same color\n bool ok(int x, int y) {\n for (int i = 0; i < m; i++) {\n if (((x >> (2*i)) & 3) == (((y >> (2*i)) & 3))) return false;\n }\n \n return true;\n }\n \n bool check(int x) {\n\t\t// check if near row has same color\n for (int i = 0; i < m - 1; i++) {\n if (((x >> (2*i)) & 3) == ((x >> (2*(i+1))) & 3)) return false;\n }\n \n\t\t// filter state 11 since there are only 3 types of color\n for (int i = 0; i < m; i++)\n if (((x >> (2*i)) & 3) == 3) return false;\n return true;\n }\n\n int colorTheGrid(int _m, int n) {\n m = _m;\n vector<vector<long long>> dp(2, vector<long long>(1<<(2*m), 0));\n for(int i = 0; i < 1 << (2*m); i++) {\n if (check(i))\n dp[0][i] = 1;\n }\n \n for (int i = 1; i < n; i++) {\n for (int j = 0; j < (1 << (2*m)); j++) {\n if (check(j)) {\n dp[i%2][j] = 0;\n for (int k = 0; k < (1 << (2*m)); k++) {\n if (check(k) && ok(j, k)) {\n dp[i%2][j] = (dp[i%2][j] + dp[(i-1)%2][k]) % M;\n }\n }\n }\n }\n }\n \n long long ans = 0;\n for (int i = 0; i < 1 << (2*m); i++) {\n ans = (ans + dp[(n-1)%2][i]) % M;\n }\n \n return ans;\n }\n};\n```
3
0
[]
0
painting-a-grid-with-three-different-colors
Python | Blazing fast O(log n) solution using modular matrix exponentiation
python-blazing-fast-olog-n-solution-usin-kob1
Intuition\nThis solution is an extension to the solution for the same problem where $m = 3$ which can be found here. \n\nFor simplicity, we use $0,1,2$ to denot
parzan
NORMAL
2024-06-11T20:24:49.844806+00:00
2024-06-11T20:24:49.844850+00:00
103
false
# Intuition\nThis solution is an extension to the solution for the same problem where $m = 3$ which can be found [here](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/solutions/5222661/python-simple-dp-and-fast-matrix-multiplication-with-full-explanation/). \n\nFor simplicity, we use $0,1,2$ to denote the colors red, green and blue (or permutations of these colors).\n\nTo solve this problem, a key component we need to understand is the answer to the question: given a column of tiles colored properly, which are the properly colored columns that can immediately follow it?\n\nAn important and helpful observation is that we can consider patterns of columns instead of specific columns. We say to columns share the same pattern if the columns are equivalent up to some permutation of the colors. For example, in the case where $m=4$, the columns $0102$ and $2021$ are clearly not equivalent but they share the same pattern (using the permutation that switches $0\\to 2, 1\\to 0, 2\\to 1$).\n\n# Approach\nGiven a value of $m$, let $p_1, p_2, \\ldots, p_k$ be the distinct patters of properly colored columns of height $m$ (for example, it\'s easy to verify that for $m=3$ there are 2 patterns and for $m=4$ there are 4 - where two are mirror symmetries of one another). Note that since $m$ is small, we can compute once, by brute force the incidence mapping that computes for each $1 \\leq i, j \\leq k$ the number of possible column coloring of pattern $p_i$ that can follow a column coloring of pattern $p_j$. This will come in handy in just a minute.\n\nLet $v$ be the $k$-length vector whose $i$-th entry is the number of properly colored columns of patter $p_i$. For example, with $m=3$ the patterns are $p_1 = 012, p_2 = 010$ and $v = \\begin{bmatrix}6\\\\6\\end{bmatrix}$. Next, let $M$ be the $k\\times k$ matrix where $M_{i,j}$ denotes the incidence described above (i.e., the number of possible column colorings of pattern $p_i$ that can follow a column coloring of pattern $p_j$). For example, in the case of $m=3$, this is the matrix $M = \\begin{bmatrix}2&2\\\\2&3\\end{bmatrix}$.\n\nWith this notation, we can see that $(Mv)_i = \\sum_{j} M_{i,j}\\cdot v_j$ is the number of possible coloring for the second column of pattern $p_i$ (and so $\\sum_i (Mv)_i$ is the total possible coloring of the second row or the answer for the query `colorTheGrid(m, 2)`). We can compute the answer for the next column by computing $M^2 \\cdot v$ and summing the values, and in general, the sum of entries in $M^k \\cdot v$ is precisely `colorTheGrid(m, k+1)` (where we remember to take modulo of the results).\n\nWith $M,v$ computed manually (and since they have dimensions at most $8 \\times 8$ for $m \\leq 5$), this already gives rise to an $O(n)$ algorithm: compute $M^{n-1}\\cdot v$ and sum the entries in the resulting vector, but we can do better. We compute $M^{n-1}$ using modular matrix exponentiation which requires only $O(\\log n)$ iterations, each one in $O(1)$ time (the matrix entries remain $O(1)$ size since we take modulo at each step of the process and so they are always bounded by $10^9+7$). See [here](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/solutions/5222661/python-simple-dp-and-fast-matrix-multiplication-with-full-explanation/) for a thorough explanation on the algorithm and a step-by-step construction of $M,v$ for the case where $m=3$.\n\nOne final touch is to notice that when $m=1,2$, the results can be computed directly. In the solution below we have manually computed the values of $M,v$ for $m=3,4,5$ and used `numpy` for algebraic operations.\n\n# Complexity\n- Time complexity:\nAs stated above, the algorithm requires $O(\\log n)$ iterations, each one in time $O(1)$, for a total of $O(\\log n)$ running time. \n\n- Space complexity:\nAs all entries of the intermediate matrices and vectors are bounded by $10^9+7$, we require $O(1)$ space.\n\nIt is worth noting that due to the small values of $n$ tested, this code performs in practice roughly as well as the simple DP approach whose runtime is around $O(2^m \\cdot n)$. However, this solution can compute values of $n$ for which the DP solution will not halt in reasonable time.\n\n\n# Code\n```\ndef colorTheGrid(self, m: int, n: int) -> int:\n M = 10**9+7\n if m == 1: return (pow(2, n-1, M)*3) % M\n if m == 2: return (pow(3, n-1, M)*6) % M\n v1 = self.choose_vec(m)\n A = self.choose_mat(m)\n A = self.modexp(A, n-1, M)\n return sum(np.matmul(A, v1)) % M\n\ndef choose_vec(self, m):\n if m == 3: return np.array([6, 6], dtype=int)\n if m == 4: return np.array([6, 12, 6], dtype=int)\n if m == 5: return np.array([6, 6, 6, 6, 6, 6, 6, 6], dtype=int)\n\ndef choose_mat(self, m):\n if m == 3: return np.array([[2, 2], [2, 3]], dtype=int)\n if m == 4: return np.array([[3, 2, 1], [4, 4, 2], [1, 1, 2]], dtype=int)\n if m == 5: return np.array([[3, 2, 2, 1, 0, 1, 2, 2],\n [2, 2, 2, 1, 1, 1, 1, 1],\n [2, 2, 2, 1, 0, 1, 2, 2],\n [1, 1, 1, 2, 1, 1, 1, 1],\n [0, 1, 0, 1, 2, 1, 0, 1],\n [1, 1, 1, 1, 1, 2, 1, 1],\n [2, 1, 2, 1, 0, 1, 2, 1],\n [2, 1, 2, 1, 1, 1, 1, 2]\n ], dtype=int)\n\ndef modexp(self, A, k, M):\n n = A.shape[0]\n res = np.identity(n, dtype=int)\n while k:\n if k % 2 == 1:\n res = np.matmul(res, A) % M\n A = np.matmul(A, A) % M\n k //= 2\n return res \n```
2
0
['Math', 'Matrix', 'Combinatorics', 'Python3']
1
painting-a-grid-with-three-different-colors
2-D DP + BitMask + Unordered Map || C++ || Well Explained
2-d-dp-bitmask-unordered-map-c-well-expl-vjck
Intuition\nThe problem requires coloring a grid of m rows and n columns such that no adjacent cells have the same color. We can approach this problem using dyna
EGhost08
NORMAL
2023-09-23T21:45:50.415169+00:00
2023-09-23T21:45:50.415193+00:00
251
false
### Intuition\nThe problem requires coloring a grid of `m` rows and `n` columns such that no adjacent cells have the same color. We can approach this problem using dynamic programming, where we keep track of the valid color masks for each cell in a row.\n\n### Approach\n1. We define a `generate_mask` function that generates valid color masks for a given cell based on the colors used in the previous cell and the cell above it. This function recursively explores the color possibilities for each cell in a row and appends valid masks to a list.\n\n2. We use dynamic programming to calculate the number of valid colorings for each cell in each row. We maintain a 2D array `dp`, where `dp[idx][msk]` represents the number of valid colorings for the cell at row `idx` with the color mask `msk`.\n\n3. We keep track of valid color masks using an unordered map `msk_map`. For each mask `msk`, we store a list of valid masks that can be used in the next row. We populate this map as we calculate the valid masks using the `generate_mask` function.\n\n4. In the `func` function, we recursively calculate the number of valid colorings for each cell in each row, taking into account the valid color masks. We use modular arithmetic to handle large numbers and avoid overflow.\n\n5. Finally, we call the `func` function to calculate the total number of valid colorings for the entire grid, starting from the first row. The result is the answer to the problem.\n\n### Time and Space Complexity\n- Time Complexity: The time complexity of this solution is $$O(n * (3^m))$$ where `n` is the number of rows and `m` is the number of columns. This is because for each cell in each row, we explore up to 3 possibilities (colors), and we do this for `n` rows.\n- Space Complexity: The space complexity is $$O(n * (3^m))$$ as well, considering the `dp` array and the `msk_map` unordered map that stores the valid masks for each row.\n\n# Code\n```\ntypedef long long ll;\nclass Solution {\n ll mod = 1e9+7;\n void generate_mask(int m,int msk,vector<int> &masks,int &pre_msk,int pre_col)\n {\n if(m==0)\n {\n masks.push_back(msk);\n return;\n }\n for(int i=1;i<=3;i++)\n if(pre_col!=i && ((pre_msk>>((m-1)*2))&3)!=i)\n generate_mask(m-1,msk|(i<<(m-1)*2),masks,pre_msk,i);\n }\n int func(int &m,int&n,int idx,int msk,vector<vector<int>> &dp,unordered_map<int,vector<int>> &msk_map)\n {\n if(idx==n)\n return 1;\n if(dp[idx][msk]!=-1)\n return dp[idx][msk];\n if(msk_map.find(msk)==msk_map.end())\n generate_mask(m,0,msk_map[msk],msk,0);\n ll ans = 0;\n for(auto cur_msk : msk_map[msk])\n {\n ans += func(m,n,idx+1,cur_msk,dp,msk_map)*1LL;\n ans %= mod;\n }\n return dp[idx][msk] = ans;\n }\npublic:\n int colorTheGrid(int m, int n) \n {\n // red = 01 | green = 10 | blue = 11\n vector<vector<int>> dp(n,vector<int>(1<<(2*m),-1));\n unordered_map<int,vector<int>> msk_map;\n return (int)func(m,n,0,0,dp,msk_map);\n }\n};\n```
2
0
['Hash Table', 'Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'C++']
0
painting-a-grid-with-three-different-colors
2 Bitmask + Dp solution
2-bitmask-dp-solution-by-hacker_antace-rozn
Intuition\n Describe your first thoughts on how to solve this problem. \nNote the memoisation. To reduce the memory usage we only memoise the i and premask as a
hacker_antace
NORMAL
2023-09-23T06:00:07.734143+00:00
2023-09-23T06:02:26.749082+00:00
427
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNote the memoisation. To reduce the memory usage we only memoise the i and premask as at j = 0, it is obvious that curmask should be zero.\n\n2 bits represents colors - \n00 -> while\n01 -> red\n10 -> yellow\n11 -> blue\n\nTo identify the prevous color and previous row color you have to analyse 2 bit at a time. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dp[1001][1<<10];\n int solve(int i, int j, int premask, int curmask, int n, int m){\n if(i == n) return 1;\n if(dp[i][premask]!=-1 && j == 0) return dp[i][premask];\n if(j == m) return solve(i + 1, 0, curmask, 0, n, m);\n long long ans = 0;\n for(int k = 1; k<=3; k++){\n if(((premask>>(2*j))&3) != k && (j == 0 || ((curmask>>(2*j-2))&3) != k)){\n ans += solve(i, j+1, premask, curmask | (k<<(2*j)), n, m);\n ans = ans%mod;\n }\n }\n if(j == 0) dp[i][premask] = ans;\n return ans;\n }\n int colorTheGrid(int m, int n) {\n memset(dp, -1, sizeof(dp));\n return solve(0, 0, 0, 0, n, m);\n }\n};\n```
2
0
['Dynamic Programming', 'Recursion', 'Memoization', 'Bitmask', 'C++']
1
painting-a-grid-with-three-different-colors
Java | Short DP (bottom-up)
java-short-dp-bottom-up-by-student2091-a8ix
Ideas\nEach column is a state, with 3^5 possible states; however, there are a lot of invalid states and base 3 is difficult to handle, so we will use 2^10, 2 bi
Student2091
NORMAL
2022-07-10T20:44:26.819440+00:00
2022-07-10T20:47:41.427888+00:00
415
false
#### Ideas\nEach column is a state, with `3^5` possible states; however, there are a lot of invalid states and base 3 is difficult to handle, so we will use `2^10`, 2 bits each to represent it. Here I\'ve chosen `00 to be invalid, and 01 -> blue, 10 -> red, 11 -> green.`\n\nThen for each configuration, we check previous configuration, then sum them up.\n#### Steps\n1. Write a `ok(a, b, m)` function that compares whether `a` and `b` shares the same 2 bits for length `2*m`.\n2. The base case is 1 when `ok(a, a>>2,m-1)` return true, 0 when false.\n3. The recurring relationship is when `ok(a,b,m)` return true and then add it up.\n\n#### Time Complexity: Worst case (48 * 2^M * N)\nThe reason for 48 is because there are at most 48 valid states for `M=5`.\n\n#### Thoughts\nYes, we can have optimized it by only travesing the valid states, but it is unncessary for getting AC.\n```Java\nclass Solution {\n public int colorTheGrid(int m, int n) {\n int A = 1 << 2*m, M = (int)1e9+7;\n int[] dp = new int[A];\n for (int i = 1; i < A; i++){\n if (ok(i,i>>2,m-1)){ // base case\n dp[i]=1;\n }\n }\n for (int i = 1; i < n; i++){\n int[] next = new int[A];\n for (int j = 0; j < A; j++){\n for (int k = 0; k < A && dp[j]>0; k++){\n if (dp[k]>0&&ok(k,j,m)){\n next[j]+=dp[k];\n next[j]%=M;\n }\n }\n }\n dp=next;\n }\n return (int)(Arrays.stream(dp).asLongStream().sum()%M);\n }\n\n private boolean ok(int a, int b, int m){\n for (int i = 0; i < m; i++, a/=4, b/=4){\n if (a%4==0||b%4==0||a%4==b%4){\n return false;\n }\n }\n return true;\n }\n}\n```
2
0
['Dynamic Programming', 'Java']
0
painting-a-grid-with-three-different-colors
dp + bitmask | brute-force dp
dp-bitmask-brute-force-dp-by-diyora13-jrqc
\nclass Solution {\npublic:\n int n,m,dp[1000][5][(1<<10)],mod=1e9+7;\n \n int sol(int i,int j,int mask)\n {\n if(i==n) return 1;\n if
diyora13
NORMAL
2022-05-31T08:23:18.516037+00:00
2022-05-31T08:23:18.516083+00:00
530
false
```\nclass Solution {\npublic:\n int n,m,dp[1000][5][(1<<10)],mod=1e9+7;\n \n int sol(int i,int j,int mask)\n {\n if(i==n) return 1;\n if(j==m) return sol(i+1,0,mask);\n \n long ans=dp[i][j][mask];\n if(ans!=-1) return ans;\n ans=0;\n \n for(int k=1;k<=3;k++)\n {\n int t=((1<<10)-1) ^ (3<<2*j); // 11 11 00(jth 00) 11 11\n int nwmask=(mask & t) ^ (k<<2*j); // change mask = 01 10 00(jth 00) 11 10 ^ 00 00 k 00 00 \n \n int up=(mask>>(2*j))%4; // mask\'s jth value in (i-1)\'s row\n int lst=0;\n if(j) lst=(mask>>(2*(j-1)))%4; // mask\'s (j-1)th value i ith row; \n \n if(k==up || k==lst) continue;\n ans+=sol(i,j+1,nwmask);\n }\n ans%=mod;\n return dp[i][j][mask]=ans;\n }\n \n int colorTheGrid(int mm, int nn) \n {\n n=nn; m=mm;\n memset(dp,-1,sizeof(dp));\n return sol(0,0,0);\n }\n};\n```
2
0
['Dynamic Programming', 'C', 'Bitmask', 'C++']
0
painting-a-grid-with-three-different-colors
My C++ Solution... with dfs and bottom up dp
my-c-solution-with-dfs-and-bottom-up-dp-n2bpc
\nclass Solution {\npublic:\n vector<string> stripes;\n vector<char> temp;\n int p = 1e9 + 7;\n int colorTheGrid(int m, int n) {\n // we want
thin_k_ing
NORMAL
2021-08-07T12:50:42.395169+00:00
2021-08-07T12:50:58.540863+00:00
388
false
```\nclass Solution {\npublic:\n vector<string> stripes;\n vector<char> temp;\n int p = 1e9 + 7;\n int colorTheGrid(int m, int n) {\n // we want to know what are the different\n // ways a single row can be filled with\n // given that the total number of columns\n // are m and we have three available colors\n dfs(m, \' \', 0);\n // now we have all the available stripes to fill a row with\n int z = stripes.size();\n vector<vector<int>> adj(z);\n for(int i = 0; i < z; i++)\n for(int j = i + 1; j < z; j++)\n if(!conflict(i, j)) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n // dp[i][j] tells us the different ways we can\n // colors m * (i + 1) table such that the last\n // stripe is stripes[j]\n vector<vector<int>> dp(n, vector<int>(z));\n for(int i = 0; i < n; i++)\n for(int j = 0; j < z; j++)\n if(i == 0) dp[i][j] = 1;\n else for(int nbr : adj[j])\n dp[i][j] = (dp[i][j] + dp[i - 1][nbr]) % p;\n int total = 0;\n for(int j = 0; j < z; j++)\n total = (total + dp[n - 1][j]) % p;\n return total;\n }\n bool conflict(int i, int j) {\n string a = stripes[i], b = stripes[j];\n for(int i = 0; i < a.size(); i++)\n if(a[i] == b[i]) return true;\n return false;\n }\n void dfs(int m, char last, int j) {\n if(j == m) {\n string s = "";\n for(char c : temp) s += c;\n stripes.push_back(s);\n } else {\n if(last != \'r\') {\n temp.push_back(\'r\');\n dfs(m, \'r\', j + 1);\n temp.pop_back();\n }\n if(last != \'b\') {\n temp.push_back(\'b\');\n dfs(m, \'b\', j + 1);\n temp.pop_back();\n }\n if(last != \'g\') {\n temp.push_back(\'g\');\n dfs(m, \'g\', j + 1);\n temp.pop_back();\n }\n }\n }\n};\n```
2
0
[]
0
painting-a-grid-with-three-different-colors
(C++) DP, Bitmask (Base 3) - Commented code for better understandability
c-dp-bitmask-base-3-commented-code-for-b-6zxb
Learnt DP with bitmasking yesterday and it feels good to have solved this problem today :)\n\nclass Solution {\npublic:\n int M, N;\n int MOD = 1e9 + 7;\n
nihargupta1512
NORMAL
2021-07-16T14:19:38.548949+00:00
2021-07-16T14:19:38.549019+00:00
756
false
Learnt DP with bitmasking yesterday and it feels good to have solved this problem today :)\n```\nclass Solution {\npublic:\n int M, N;\n int MOD = 1e9 + 7;\n \n // function to fetch the (M-b-1)th bit of the mask with base 3\n int isEqual(int a, int b, int x)\n {\n if(a == -1)\n return false;\n for(int i=0;i<(M-b-1);i++)\n a = a/3;\n return a%3 == x;\n }\n \n void generate_masks(int prevMask, int currMask, int i, vector<int> &currMasks)\n {\n // if we have reached the end of row, store the current mask calculated and then backtrack.\n if(i == M)\n {\n currMasks.push_back(currMask);\n return;\n }\n \n // The 1st if condition (isEqual call) is to ensure grid[i][j] != grid[i][j-1]\n // The 2nd if condition (currMask%3) is to ensure grid[i][j] != grid[i-1][j]\n \n // assign red -> 0\n if(!isEqual(prevMask,i,0) && (i == 0 || currMask%3 != 0))\n generate_masks(prevMask, currMask*3, i+1, currMasks);\n \n // assign green -> 1\n if(!isEqual(prevMask,i,1) && (i == 0 || currMask%3 != 1))\n generate_masks(prevMask, currMask*3+1, i+1, currMasks);\n \n // assign blue -> 2\n if(!isEqual(prevMask,i,2) && (i == 0 || currMask%3 != 2))\n generate_masks(prevMask, currMask*3+2, i+1, currMasks);\n }\n\n int fun(vector<int> currMasks, int j, vector<vector<int>> &dp1, vector<vector<int>> &dp2)\n {\n // reached end of columns\n if(j == N)\n return 1;\n \n long long int ans = 0;\n for(int i=0;i<currMasks.size();i++)\n {\n int mask = currMasks[i];\n // if the current (j,mask) pair is already present in the dp, use it\n if(dp1[j][mask])\n {\n dp1[j][mask] = dp1[j][mask];\n }\n // if the current mask\'s next set of masks are already present in the dp, use it\n else if(dp2[mask].size())\n {\n dp1[j][mask] = fun(dp2[mask], j+1, dp1, dp2);\n }\n // else generate the next column\'s masks and calculate the answer recursively\n else\n {\n vector<int> nextMasks;\n generate_masks(mask, 0, 0, nextMasks);\n dp2[mask] = nextMasks;\n\n dp1[j][mask] = fun(nextMasks, j+1, dp1, dp2);\n }\n // answer for the current column till the end is the sum of: dp1[a][0] to dp1[a][242]\n ans = (ans + dp1[j][mask]) % MOD;\n }\n return ans;\n }\n \n int colorTheGrid(int m, int n) {\n vector<int> currMasks;\n M = m; N = n;\n \n // dp1[a][b] stores the number of possible combinations for column a and mask b. Our answer will be the sum of: dp1[a][0] to dp1[a][242].\n vector<vector<int>> dp1(N, vector<int>(243));\n \n // dp2 is being used to avoid multiple calculations for following cases:\n // if column A has a bitmask M, then column A+1 will always have the same number of possible bitmasks. We can calculate all of them at once and store them in dp2[M].\n vector<vector<int>> dp2(243, vector<int>());\n \n // generate all possible bitmasks for column 1\n generate_masks(-1, 0, 0, currMasks);\n \n return fun(currMasks, 0, dp1, dp2);\n }\n};\n```\nPlease feel free to drop any questions or suggestions in the comments.\n\nTrying to figure out the time complexity but finding it a bit difficult right now. Any help is appreciated!
2
0
[]
1
painting-a-grid-with-three-different-colors
Easy Java, comments, 28ms, O(n*P*P) complexity, memory O(P), where P is column permutations count
easy-java-comments-28ms-onpp-complexity-kq2fm
\nclass Solution {\n public int colorTheGrid(int m, int n) {\n //each permutation will be encoded as Long where every color will be packed into 0xFF b
dimitr
NORMAL
2021-07-13T06:30:50.254072+00:00
2021-07-13T06:35:30.615948+00:00
311
false
```\nclass Solution {\n public int colorTheGrid(int m, int n) {\n //each permutation will be encoded as Long where every color will be packed into 0xFF byte \n //for example RGB combination will be represented as 0x010204\n //while BGRGB combination will be 0x0402010204\n final long R = 1;\n final long G = 2;\n final long B = 4;\n final int MOD =1000000007;\n \n //compute overall number of possible permutations for a single column\n int COUNT = 3;\n for(int i=0;i<m-1;i++)\n COUNT*=2;\n \n long[] perms = new long[COUNT];\n Queue<Long> q = new LinkedList<>();\n \n q.add(R);\n q.add(G);\n q.add(B);\n \n //fill in all possible permuatations using Queue\n int ind = COUNT;\n while(!q.isEmpty()){\n Long l = q.poll();\n if( l >= 1L << 8*(m-1) ) //m-length permutation\n perms[--ind] = l;\n else{\n if( (l & R) != 0 ){\n q.add( (l<<8) + G);\n q.add( (l<<8) + B);\n }else if( (l & B) != 0 ){\n q.add( (l<<8) + R);\n q.add( (l<<8) + G);\n }else{\n q.add( (l<<8) + R);\n q.add( (l<<8) + B);\n }\n }\n }\n \n \n \n int[] prev = new int[COUNT];\n int[] curr = new int[COUNT];\n Arrays.fill(prev, 1);\n \n //iterate by columns from left to right, \n //memorizing score count for every permutation in previous column\n for(int iter=0;iter<n-1;iter++){\n for(int i=0;i<COUNT;i++){\n for(int j=0;j<COUNT;j++){\n if((perms[i] & perms[j]) == 0) // both are OK to each other \n curr[j] = (curr[j]+prev[i])%MOD;\n\n }\n }\n //swap buffers and erase\n int[] t = prev;\n prev = curr;\n curr = t;\n Arrays.fill(curr,0);\n }\n \n //accumulate all scores for permuttions as per last collumn \n int result = 0;\n for(int i=0;i<COUNT;i++)\n result = (result + prev[i])%MOD;\n \n return result; \n }\n}\n```
2
0
[]
0
painting-a-grid-with-three-different-colors
Python3. DFS (top down dp) without bit masking
python3-dfs-top-down-dp-without-bit-mask-40ch
\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n column_patterns = []\n \n\t\t# collect all column patterns with using back
yaroslav-repeta
NORMAL
2021-07-12T17:03:26.393140+00:00
2021-07-12T17:06:58.535278+00:00
158
false
```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n column_patterns = []\n \n\t\t# collect all column patterns with using backtracking\n def backtrack(pattern):\n if len(pattern) == m:\n column_patterns.append(pattern)\n else:\n for i in range(3):\n if not pattern or i != pattern[-1]:\n backtrack(pattern + [i])\n\n backtrack([])\n\n\t\t# for each column pattern find all compatible ones\n compatible_patterns = [[] for _ in column_patterns]\n for i in range(len(column_patterns)):\n for j in range(i + 1, len(column_patterns)):\n for k in range(m):\n if column_patterns[i][k] == column_patterns[j][k]:\n break\n else:\n compatible_patterns[i].append(j)\n compatible_patterns[j].append(i)\n\n compatible_patterns.append(list(range(len(column_patterns)))) # pseudo column that compatible with all to start dfs\n mod = 10 ** 9 + 7\n\n\t\t# straightforward dp\n @cache\n def dfs(i, n):\n if n == 0:\n return 1\n count = 0\n for j in compatible_patterns[i]:\n count = (count + dfs(j, n - 1)) % mod\n return count\n return dfs(-1, n)\n \n```
2
0
[]
0
painting-a-grid-with-three-different-colors
Python top-down DP
python-top-down-dp-by-lixuanji-84ei
We represent cells with an integer, so the row "rgb" -> (0,1,2) \n\nThis is the core dp function, counting the number of valid colourings of a mxn grid with th
lixuanji
NORMAL
2021-07-11T04:35:53.337326+00:00
2021-07-11T04:39:31.397184+00:00
232
false
We represent cells with an integer, so the row "rgb" -> `(0,1,2)` \n\nThis is the core dp function, counting the number of valid colourings of a `mxn` grid with the constraint that the topmost row must be able to be placed below a row `prev`\n\n```\n@lru_cache(None) \ndef ans(self, n, prev):\n\tif n == 0: return 1\n\tret = 0\n\tfor s in self.states: \n\t\tif ok2(s, prev):\n\t\t\tret += self.ans(n-1,s)\n\t\t\tret %= MODULUS\n\treturn ret % MODULUS\n```\n\nWe have the functions `ok1` and `ok2` to compute when a row is valid, and when two valid rows can be placed adjacently\n\n```\ndef ok1(self, seq):\n\tfor i in range(self.m-1):\n\t\tif seq[i] == seq[i+1]: return False\n\treturn True\n\t\t\ndef ok2(s1, s2):\n for i in range(len(s1)):\n if s1[i] == s2[i]: return False\n return True\n```\n\nThe final solution prepopulates the set of valid rows, `self.state`\n\n```\nclass Solution: \n def colorTheGrid(self, m: int, n: int) -> int:\n self.m = m\n self.states = []\n\n for seq in itertools.product([0,1,2], repeat=m):\n if self.ok1(seq):\n self.states += [seq]\n \n return self.ans(n, (-1,)*m)\n```
2
0
[]
0
painting-a-grid-with-three-different-colors
Java | 100% faster | Generalized
java-100-faster-generalized-by-mangostic-8mx3
This is a generalized solution of any n and any m.\n\nThe code looks complicated, but the logic is quite easy. Although the code is long, the solution has by fa
MangoStickyRise
NORMAL
2021-07-11T04:19:12.013797+00:00
2021-07-11T19:36:24.986936+00:00
670
false
This is a **generalized** solution of any `n` and any `m`.\n\nThe code looks complicated, but the logic is quite easy. Although the code is long, the solution has by far the best performance.\n\nSay, `m = 5`. We name the color as numbers: `0, 1, 2`\n\nSteps:\n1. For each line, we have limited `patterns`, eg, `01010`, `01012`... We store the patterns in `patterns` as Strings.\n2. For each `pattern`, we record the eligible neighbors in `nexts`. Eg, for `01010`, its eligible neighbors are `10101`, `10102`...\n3. We just loop `n` times to let the count of each `pattern` roll.\n4. The final result would be the sum of all the counts, then timed by 3.\n\n\n```java\nclass Solution {\n private int mod = 1000000007;\n \n private void expand(int[] list, int ind, List<String> patterns, Map<String, Integer> indices) {\n if (ind == list.length) {\n StringBuilder pattern = new StringBuilder();\n for (int num : list) pattern.append(num);\n indices.put(pattern.toString(), patterns.size());\n patterns.add(pattern.toString());\n return;\n }\n for (int candidate = 0; candidate < 3; candidate++) {\n if (candidate != list[ind - 1]) {\n list[ind] = candidate;\n expand(list, ind + 1, patterns, indices);\n }\n }\n }\n \n private void expand2D (int[] list, int[] nextList, int ind, List<String> patterns, Map<String, Integer> indices, List<Integer> next) {\n if (ind == list.length) {\n int offset = 3 - nextList[0];\n StringBuilder pattern = new StringBuilder();\n for (int num : nextList) pattern.append((num + offset) % 3);\n next.add(indices.get(pattern.toString()));\n return;\n }\n for (int candidate = 0; candidate < 3; candidate++) {\n if (candidate != nextList[ind - 1] && candidate != list[ind]) {\n nextList[ind] = candidate;\n expand2D(list, nextList, ind + 1, patterns, indices, next);\n }\n }\n }\n \n public int colorTheGrid(int m, int n) {\n\t\tif (n < m) {\n\t\t\tint temp = m;\n\t\t\tm = n;\n\t\t\tn = temp;\n\t\t}\n // all are starting from red\n if (m == 1) {\n int[] paintLine = new int[n];\n paintLine[n - 1] = 1;\n for (int j = n - 2; j >= 0; j--) paintLine[j] = (paintLine[j + 1] * 2) % mod;\n return (int)((long)paintLine[0] * 3 % mod);\n }\n \n // get all patterns\n List<String> patterns = new ArrayList<>();\n Map<String, Integer> indices = new HashMap<>();\n int[] list = new int[m];\n list[0] = 0;\n expand(list, 1, patterns, indices);\n int p = patterns.size();\n \n if (n == 1) return 3 * p;\n \n // get all nexts\n List<List<Integer>> nexts = new ArrayList<>();\n for (int i = 0; i < p; i++) {\n List<Integer> next = new ArrayList<>();\n nexts.add(next);\n String string = patterns.get(i);\n list = new int[m];\n for (int chi = 0; chi < m; chi++) list[chi] = string.charAt(chi) - \'0\';\n int[] nextList = new int[m];\n for (int candidate = 0; candidate < 3; candidate++) {\n if (candidate != list[0]) {\n nextList[0] = candidate;\n expand2D(list, nextList, 1, patterns, indices, next);\n }\n }\n }\n \n // calculate\n int[] counts = new int[p];\n Arrays.fill(counts, 1);\n for (int round = 0; round < n - 1; round++) {\n int[] temp = new int[p];\n for (int pi = 0; pi < p; pi++) {\n List<Integer> next = nexts.get(pi);\n for (int ni : next) {\n temp[pi] += counts[ni];\n temp[pi] %= mod;\n }\n }\n counts = temp;\n }\n \n int res = 0;\n for (int count : counts) {\n res += count;\n res %= mod;\n }\n return (int)((long)res * 3 % mod);\n }\n}\n```\n\nIn the end,\n\nThere may be some solutions which predefines the neighboring relationships, that have better performances.\nThe aim of this solution is to illustrate the idea and generalize it.
2
0
[]
1
painting-a-grid-with-three-different-colors
C++ O(n * (3^m) * f) DFS + DP
c-on-3m-f-dfs-dp-by-mingrui-d8i5
The idea is to calculate all next column states from a previous column state (3^m). Then we can DP on each column.\nEach state is compressed into an int (curr,
mingrui
NORMAL
2021-07-11T04:06:27.855697+00:00
2021-07-11T04:59:14.066440+00:00
438
false
The idea is to calculate all next column states from a previous column state (3^m). Then we can DP on each column.\nEach state is compressed into an int (`curr`, `pre`, `hmap`\'s key) in which each adjacent two bits indicates a choice of color (00 as white).\n`hmap` counts the number of occurances of each state.\nA minor improvement can be done by caching the genNexts results for each state but it won\'t improve complexity.\nOver all complexity is `O(n * (3^m) * f)`. `f` is the fan-out number related to `m` (average length of `nexts`) which is not large when `m = 5`.\n```\nclass Solution {\n vector<int> nexts;\n void genNexts(int m, int i, int curr, int pre) {\n if (i == m) {\n nexts.push_back(curr);\n return;\n }\n int a = (pre >> (i * 2)) & 3;\n int b = 0;\n if (i > 0) {\n b = curr >> ((i - 1) * 2);\n }\n for (int j = 1; j < 4; j++) {\n if (j == a || j == b) {\n continue;\n }\n genNexts(m, i + 1, curr | (j << (i * 2)), pre);\n }\n }\npublic:\n int colorTheGrid(int m, int n) {\n constexpr int mod = 1e9 + 7;\n unordered_map<int, int> hmap;\n hmap[0] = 1;\n for (int i = 0; i < n; i++) {\n unordered_map<int, int> hmap2;\n for (const auto &it : hmap) {\n nexts.clear();\n genNexts(m, 0, 0, it.first);\n for (int next : nexts) {\n hmap2[next] = (hmap2[next] + it.second) % mod;\n }\n }\n hmap = hmap2;\n }\n int result = 0;\n for (const auto &it : hmap) {\n result = (result + it.second) % mod;\n }\n return result;\n }\n};\n```
2
0
[]
1
painting-a-grid-with-three-different-colors
Simple Top Down recursive DP + bitmask. Generate all valid combination first.
simple-top-down-recursive-dp-bitmask-gen-lyxe
Code
Michael_Teng6
NORMAL
2025-04-09T19:18:22.705555+00:00
2025-04-09T19:18:22.705555+00:00
6
false
# Code ```cpp [] class Solution { public: int m,n; int mod=1e9+7; int dp[1000][32][32]; int dfs(int currow,int previgreen,int previblue,vector<pair<int,int>>& masks) { if(currow==n) return 1; if(dp[currow][previgreen][previblue]!=-1) return dp[currow][previgreen][previblue]; long long ans=0; int previousred=previgreen^previblue; for(auto it:masks) { int tempgreen=it.first,tempblue=it.second; int tempred=tempgreen^tempblue; bool redok=true; for(int i=0;i<m;i++) { if(((previousred >> i) & 1)==0&&((tempred >> i)&1) == 0) { redok=false; break; } } if(currow==0||((tempgreen&previgreen)==0&&(tempblue&previblue)==0&&redok)) { ans+=dfs(1+currow,tempgreen,tempblue,masks); ans%=mod; } } return dp[currow][previgreen][previblue]=ans; } void getmask(int indx,int isgreen,int isblue,int previous,vector<pair<int,int>>& masks) { if(indx==m) { masks.push_back({isgreen,isblue}); return; } for(int i=0;i<3;i++) { if(i!=previous) { if(i==0) getmask(indx+1,isgreen,isblue,i,masks);//red else if(i==1) getmask(indx+1,isgreen|(1<<indx),isblue,i,masks);//green else getmask(indx+1,isgreen,isblue|(1<<indx),i,masks);//blue } } } int colorTheGrid(int mcol, int nrow) { m=mcol; n=nrow; vector<pair<int,int>> masks; getmask(0,0,0,-1,masks); memset(dp,-1,sizeof(dp)); return dfs(0,0,0,masks); } }; ```
1
0
['Dynamic Programming', 'Depth-First Search', 'Recursion', 'Memoization', 'Bitmask', 'C++']
0
painting-a-grid-with-three-different-colors
Simplest Explanation | | Thought Process | | Why Bitmasking
simplest-explanation-thought-process-why-qj8t
IntuitionTo solve this problem, let's analyze the given constraints and requirements: We have a grid of size m × n. We can only use 3 colors to paint the grid.
UKS_28
NORMAL
2025-02-09T16:20:43.630369+00:00
2025-02-09T16:20:43.630369+00:00
102
false
# Intuition To solve this problem, let's analyze the given constraints and requirements: - We have a grid of size **m × n**. - We can only use **3 colors** to paint the grid. - No two adjacent cells (horizontally or vertically) can have the same color. ### Initial Thoughts A brute force approach would be to assign colors to each cell one by one, ensuring no adjacent cells share the same color. However, this method involves excessive backtracking, making it inefficient. Instead, a more structured approach is: 1. **Column-wise Coloring:** Start by filling each column sequentially while ensuring no adjacent colors are the same. 2. **Track Color Configurations Efficiently:** To avoid recomputing, store previously used column configurations and use them for future calculations. 3. **Bit Masking for Optimization:** Each column can be represented using bit masking, allowing us to encode its color pattern efficiently. ### Bit Masking Representation Each cell can have one of three colors: - **Red (01)** - **Blue (10)** - **Green (11)** Thus, a column of `m` rows can be represented using a `2m`-bit integer. For example, if a column is `[R, B, R, G, B]`, its bit representation would be: ``` [01(R) 10(B) 01(R) 11(G) 10(B)] → 0110011110 ``` Since `m ≤ 5`, the maximum number of bits required is `10`, meaning there are at most `1024` possible column configurations. # Approach ### Steps to Solve the Problem 1. **Start from the first column** and paint its rows according to the constraints. 2. **Recursive Traversal:** Move to the next column and continue painting while ensuring: - The current cell’s color differs from the left and top adjacent cells. 3. **Use Memoization:** Store results for previously computed column configurations to avoid redundant computations. 4. **Base Case:** If we reach the last column, return `1` as a valid configuration. 5. **Bit Manipulation to Extract Colors:** - Extract the left-adjacent cell’s color from the previous column. - Extract the top-adjacent cell’s color from the current column. 6. **Try all possible colors (****`1, 2, 3`****)** and recursively compute valid grid configurations. 7. **Store and Return Results:** Memoize results for each unique column configuration to improve efficiency. # Complexity Analysis - **Time Complexity:** Since we use bit masking and memoization to store previously computed results, the time complexity is approximately **O(n × 3^m)**, which is manageable for small values of `m` and `n`. - **Space Complexity:** **O(n × 1024)** for memoization, as there are at most `1024` unique column configurations. # Code Implementation ```cpp class Solution { public: long long MOD; vector<vector<long long>> dp; long long fun(long long column, long long row, long long lastcolColor, long long currcolColor, int m, int n) { if (row == m) { row = 0; lastcolColor = currcolColor; currcolColor = 0; return fun(column + 1, row, lastcolColor, currcolColor, m, n) % MOD; } if (column == n) return 1; if (row == 0 && dp[column][lastcolColor] != -1) return dp[column][lastcolColor]; // Extract left-adjacent color long long isred = lastcolColor & (1LL << (2 * row)); long long isblue = lastcolColor & (1LL << (2 * row + 1)); long long isgreen = isred && isblue; long long leftCol = isgreen ? 3 : (isblue ? 2 : (isred ? 1 : 0)); // Extract top-adjacent color long long upCol = 0; if (row != 0) { long long isred = currcolColor & (1LL << (2 * (row - 1))); long long isblue = currcolColor & (1LL << (2 * (row - 1) + 1)); long long isgreen = isred && isblue; upCol = isgreen ? 3 : (isblue ? 2 : (isred ? 1 : 0)); } long long res = 0; for (long long j = 1; j <= 3; j++) { if (j != upCol && j != leftCol) { res = (res % MOD + fun(column, row + 1, lastcolColor, currcolColor | (j * (1 << (2 * row))), m, n) % MOD) % MOD; } } if (row == 0) dp[column][lastcolColor] = res; return res; } int colorTheGrid(int rows, int cols) { MOD = 1e9 + 7; dp.resize(1001, vector<long long>(1025, -1)); return fun(0, 0, 0, 0, rows, cols); } }; ``` # Summary - We used **bit masking** to efficiently store and track column color patterns. - **Recursive DP with memoization** helps optimize redundant calculations. - The approach ensures valid color assignments by checking adjacent constraints. - This method is feasible for `m ≤ 5` and `n ≤ 1000` due to the optimized state space. This approach provides an efficient way to solve the problem while ensuring optimal time and space complexity. 🚀
1
0
['C++']
0
painting-a-grid-with-three-different-colors
Simple 3D dp Solution
simple-3d-dp-solution-by-ammar-a-khan-i8xx
Code
ammar-a-khan
NORMAL
2025-02-05T15:18:38.489881+00:00
2025-02-05T15:18:38.489881+00:00
79
false
# Code ```cpp int mod = 1000000007; //memoization soln int helper(int i, int j, int mask, int &m, int &n, vector<vector<vector<int>>> &dp){ //mask:[0, i) stores mask for curr col, rest for prev col if (i == n){ return 1; } if (dp[i][j][mask] == -1){ //compute if not already int count = 0; int curr0 = j*2, curr1 = j*2 + 1, prev0 = j*2 - 2, prev1 = j*2 - 1; if (j == m){ count = helper(i + 1, 0, mask, m, n, dp); } else { if ((mask&(1<<curr0)) > 0 || (mask&(1<<curr1)) == 0){ //red if (j == 0 || (mask&(1<<prev0)) > 0 || (mask&(1<<prev1)) == 0){ count = (count + helper(i, j + 1, (mask&(~(1<<curr0)))|(1<<curr1), m, n, dp))%mod; } } if ((mask&(1<<curr0)) == 0 || (mask&(1<<curr1)) > 0){ //green if (j == 0 || (mask&(1<<prev0)) == 0 || (mask&(1<<prev1)) > 0){ count = (count + helper(i, j + 1, (mask|(1<<curr0))&(~(1<<curr1)), m, n, dp))%mod; } } if ((mask&(1<<curr0)) == 0 || (mask&(1<<curr1)) == 0){ //blue if (j == 0 || (mask&(1<<prev0)) == 0 || (mask&(1<<prev1)) == 0){ count = (count + helper(i, j + 1, (mask|(1<<curr0))|(1<<curr1), m, n, dp))%mod; } } } dp[i][j][mask] = count; } return dp[i][j][mask]; } int colorTheGrid(int m, int n){ vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(m + 1, vector<int>(pow(2, 2*m), -1))); //3D dp array return helper(0, 0, 0, m, n, dp); } //tabulation yumpossible due to j = 0 prolly ```
1
0
['Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'C++']
0
painting-a-grid-with-three-different-colors
The most readable solution without bitmask (and beats 73%)!
the-most-readable-solution-without-bitma-wznn
Intuition\nThere are at most 5 rows. So there are at most $3\cdot2^4 = 48$ possible ways to fill a column. This problem can be simplified to this: choose with r
kunix
NORMAL
2024-04-11T04:34:48.469307+00:00
2024-04-11T04:34:48.469338+00:00
66
false
# Intuition\nThere are at most 5 rows. So there are at most $3\\cdot2^4 = 48$ possible ways to fill a column. This problem can be simplified to this: choose with repitition $n$ columns from a set of columns such that no adjacent cells have the same color.\n\nConsidering filling the grid from left to right column by column. The choice of the $i^{th}$ column should only depend on $(i-1)^{th}$ column, but not any column before that. And since there are at most 48 possible choices of columns, we can precompute all the columns that can be neighbors. This way the problem is further simplified to: given a set of columns, and a table that for each possible column all possible columns you can choose next, find the number of possible ways to choose n columns.\n\n# Approach\n1. find all possible ways to fill columns without adjacent same color tile, name it `all_possible_cols`.\n2. for each column in `all_possible_cols`, find all possible columns that can be put next to it. The result will be a table `match_table` where $j\\in match_table[i] \\iff$ `all_possible_cols[i]` and `all_possible_cols[j]` can be neighbors.\n3. start with each of `all_possible_cols` as the first column in the grid, recursively calculate the possible ways to fill a grid.\n\n# Complexity\n- Time complexity:\nIt takes $O(c^m)$ to calculate all possible columns. Then to find the `match_table`, it squared the number of possible columns, so $O(c^{2m})$.\nFinally the recursive call (DFS) with cache, is about $O(c^mn)$. Since m is small and c is small, this can be considered $O(n)$.\n\n- Space complexity:\nThe recursion makes it a bit hard to approximate the space complexity.\n * all possible columns take $O(c^mm)$ space.\n * match table takes $O(C^{2m})$ space. Maybe it\'s less. What\'s the order for the number of candidates a column with length $m$ can have?\n * the recursive call takes $O(c^mn)$ space for the cache. The stack for the recursive call is $O(n)$.\nOverall the space complexity is $O(c^mn)$ ~ $O(n)$ given small c and m.\n\n# Code\n```\nfrom enum import Enum\nfrom functools import cache\n\nMOD = int(1e9 + 7)\n\nclass Color(Enum):\n R = 0\n G = 1\n B = 2\n\n\ndef generate_possible_column_fills(m, filled = []) -> List[List[Color]]:\n """Generate all the possible ways to fill a single column with size m"""\n if len(filled) == m:\n return [filled]\n results = []\n for c in Color:\n if filled and filled[-1] == c:\n continue\n results.extend(generate_possible_column_fills(m, filled + [c]))\n return results\n\ndef try_match(cols) -> List[List[int]]:\n """Try match columns to each other.\n\n Assumes:\n all columns are valid. I.e.\n col[j] != cols[i][j+1] for all col in cols for all j < m-1\n \n Returns:\n a list "matched", where len(matched) == len(cols) and\n matched[i] is a list [j1, j2, j3, ...] with indices to all columns that would match\n cols[i]. Where a "match" means they can be neighbors. There will be no two adjacent\n cells having the same color. I.e.\n cols[i][k] != cols[j][k] for all k < m and for all j in matched[i]\n """\n def match(col1, col2):\n return all(a != b for a, b in zip(col1, col2))\n\n ncols = len(cols)\n result = []\n for i in range(ncols):\n result.append([])\n for i in range(ncols):\n for j in range(i+1, ncols):\n if match(cols[i], cols[j]):\n result[i].append(j)\n result[j].append(i)\n return result\n\n\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n all_possible_columns = generate_possible_column_fills(m)\n col_match_table = try_match(all_possible_columns)\n\n @cache\n def n_possible_col_fill(filled_col_idx, n_cols_to_fill):\n """Returns the number of possible ways to fill a grid.\n\n Args:\n filled_col_idx: the index to some known column lists (all_possible_columns).\n This col is considered already filled into the grid, and is neighbor to \n the first empty column to be filled.\n n_cols_to_fill: number of *remaining* columns to fill. The filled column is *not*\n included.\n col_match_table: a list of list of indices. col_match_table[i] include all indices\n of columns that can be neighbor of column i, all these indices are to some known\n column lists (all_possible_columns)\n """\n if n_cols_to_fill == 0:\n return 1\n answer = 0\n for icol in col_match_table[filled_col_idx]:\n answer = (answer + n_possible_col_fill(icol, n_cols_to_fill - 1)) % MOD\n return answer\n answer = 0\n for icol in range(len(all_possible_columns)):\n answer = (answer + n_possible_col_fill(icol, n-1)) % MOD\n return answer\n \n```
1
0
['Python3']
0
painting-a-grid-with-three-different-colors
A elegant ruby solution
a-elegant-ruby-solution-by-safiir-sgry
ruby\nrequire "matrix"\n\n# @param {Integer} m\n# @param {Integer} n\n# @return {Integer}\ndef color_the_grid(m, n)\n mod = 10**9 + 7\n dp = m == 1 ? [[3]] :
safiir
NORMAL
2023-05-06T07:51:18.809512+00:00
2023-05-06T07:51:18.809545+00:00
15
false
```ruby\nrequire "matrix"\n\n# @param {Integer} m\n# @param {Integer} n\n# @return {Integer}\ndef color_the_grid(m, n)\n mod = 10**9 + 7\n dp = m == 1 ? [[3]] : [[6]] * (2**(m - 2))\n (Matrix[*$matrixs[m - 1]]**(n - 1) * Matrix[*dp]).sum % mod\nend\n\n$matrixs = [\n [[2]],\n [[3]],\n [[3, 2], [2, 2]],\n [[3, 2, 1, 2], [2, 2, 1, 2], [1, 1, 2, 1], [2, 2, 1, 2]],\n [\n [3, 2, 2, 1, 0, 1, 2, 2],\n [2, 2, 2, 1, 1, 1, 1, 1],\n [2, 2, 2, 1, 0, 1, 2, 2],\n [1, 1, 1, 2, 1, 1, 1, 1],\n [0, 1, 0, 1, 2, 1, 0, 1],\n [1, 1, 1, 1, 1, 2, 1, 1],\n [2, 1, 2, 1, 0, 1, 2, 1],\n [2, 1, 2, 1, 1, 1, 1, 2]\n ]\n]\n```
1
0
['Dynamic Programming', 'Ruby']
0
painting-a-grid-with-three-different-colors
Explained Solution
explained-solution-by-rkkumar421-5qgp
Approach\nWe are using integer as bit mask to pass which color have we used as we can only use 1,2,3 color .\n\n# Complexity\n- Time complexity: O(NM2^M*2)\n Ad
rkkumar421
NORMAL
2023-01-13T06:00:14.009049+00:00
2023-01-13T06:00:14.009098+00:00
198
false
# Approach\nWe are using integer as bit mask to pass which color have we used as we can only use 1,2,3 color .\n\n# Complexity\n- Time complexity: O(N*M*2^M*2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int dp[1001][1024] = {};\n // i col(0,1,2,3..m-1) and j row(0,1,2,..n-1) cur is current column pattern and pr is previous column pattern\n // we can have 4 states in every cell so 2 bits to define and to make full pattern if m = 5 then we will need 1024 bits\n int solve(int i, int j, int m, int n, int cur, int pr){\n if(j == n) return 1; // if we reach end row\n if(i == 0 && dp[j][pr] != 0) return dp[j][pr]; // if we go for new row and column start at 0 so we check if we got previous state before or not\n // Now we try to fill j, i place according to it\'s up and left side\n // pr : 1 2 3 1 2\n // cur: 2 3 \n // above we can see we can only fill 1 here\n int left = i == 0 ? 0 : (cur>>2*(i-1))&3; // here we see cur bits just left side \n int up = j == 0? 0 : (pr>>(2*i))&3; // here we see upwards bits in pr\n long int ans = 0;\n // here we are trying to fill colors 1 or 2 or 3\n for(int color = 1;color<=3;color++){\n if(color != left && color != up){\n if(i == m-1) ans += solve(0,j+1,m,n,0,(cur|(color<<(2*i))));\n else ans += solve(i+1,j,m,n,(cur|(color<<(2*i))),pr);\n ans = ans%(1000000007); \n }\n }\n if(i == 0) dp[j][pr] = ans; // if we got first col then reserve this state\n return ans;\n }\n int colorTheGrid(int m, int n) {\n return solve(0,0,m,n,0,0);\n }\n};\n```
1
0
['Dynamic Programming', 'Bit Manipulation', 'Memoization', 'C++']
0
painting-a-grid-with-three-different-colors
JAVA||O(3*2^(m-1)*n)||EASY UNDERSTANDING||
javao32m-1neasy-understanding-by-asppand-a22q
\nclass Solution \n{\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])\n {\n if(n=
asppanda
NORMAL
2022-05-22T08:57:43.216090+00:00
2022-05-22T08:59:11.519978+00:00
297
false
```\nclass Solution \n{\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n public static void val(ArrayList<String> arr,int color,int m,String s)\n {\n if(m==0)\n {\n arr.add(s);\n return;\n }\n for(int i=0;i<3;i++)\n {\n if(color!=i)\n val(arr,i,m-1,s+i);\n }\n }\n public static boolean Match(String s,String s1)\n {\n for(int i=0;i<s.length();i++)\n {\n if(s.charAt(i)==s1.charAt(i))\n {\n return false;\n }\n }\n return true;\n }\n public int colorTheGrid(int m, int n)\n {\n ArrayList<String> arr=new ArrayList<String>();\n for(int i=0;i<3;i++)\n {\n String s="";\n val(arr,i,m-1,s+i);\n }\n ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>();\n for(int i=0;i<arr.size();i++)\n {\n adj.add(new ArrayList<Integer>());\n }\n \n for(int i=0;i<adj.size();i++)\n {\n for(int j=0;j<arr.size();j++)\n {\n if(Match(arr.get(i),arr.get(j)))\n {\n adj.get(i).add(j);\n }\n }\n }\n int dp[][]=new int[n+1][adj.size()+1];\n for(int i=0;i<=n;i++)\n {\n Arrays.fill(dp[i],-1);\n }\n int sum12=0;\n for(int i=0;i<arr.size();i++)\n {\n sum12=(sum12%mod+dfs(n-1,adj,i,dp)%mod)%mod;\n }\n return sum12;\n \n }\n}\n```\nsuppose u have to find the adjacent column u can simply find the column combination using bitmasking \nfor example\n```\n public static void val(ArrayList<String> arr,int color,int m,String s)\n {\n if(m==0)\n {\n arr.add(s);\n return;\n }\n for(int i=0;i<3;i++)\n {\n if(color!=i)\n val(arr,i,m-1,s+i);\n }\n }\n```\n\n\n```\nu will get suppose we take m=5 and n=5\n[01010, 01012, 01020, 01021, 01201, 01202, 01210, 01212, 02010, 02012, 02020, 02021, 02101, 02102, 02120, 02121, 10101, 10102, 10120, 10121, 10201, 10202, 10210, 10212, 12010, 12012, 12020, 12021, 12101, 12102, 12120, 12121, 20101, 20102, 20120, 20121, 20201, 20202, 20210, 20212, 21010, 21012, 21020, 21021, 21201, 21202, 21210, 21212]\nwhere 0=Red 1=Green 2=Blue\nthen u can simply find which elements connect which element will connect to which element means which element is appropriate for next column\n0->[16, 17, 19, 20, 21, 28, 29, 31, 32, 33, 35, 36, 37]\n1->[16, 18, 19, 20, 28, 30, 31, 32, 34, 35, 36]\n2->[16, 17, 20, 21, 23, 28, 29, 32, 33, 36, 37, 39]\n3->[17, 21, 22, 23, 29, 33, 37, 38, 39]\n4->[18, 24, 25, 26, 30, 34]\n5->[18, 19, 24, 26, 27, 30, 31, 34, 35]\n6->[16, 17, 19, 27, 28, 29, 31, 32, 33, 35]\n7->[16, 18, 19, 26, 27, 28, 30, 31, 32, 34, 35]\n8->[16, 17, 19, 20, 21, 32, 33, 35, 36, 37, 44, 45]\n9->[16, 18, 19, 20, 32, 34, 35, 36, 44]\n10->[16, 17, 20, 21, 23, 32, 33, 36, 37, 39, 44, 45, 47]\n11->[17, 21, 22, 23, 33, 37, 38, 39, 45, 46, 47]\n12->[22, 23, 38, 39, 40, 41, 42, 46, 47]\n13->[22, 38, 40, 42, 43, 46]\n14->[20, 21, 23, 36, 37, 39, 41, 44, 45, 47]\n15->[21, 22, 23, 37, 38, 39, 40, 41, 45, 46, 47]\n16->[0, 1, 2, 6, 7, 8, 9, 10, 40, 41, 42, 46, 47]\n17->[0, 2, 3, 6, 8, 10, 11, 40, 42, 43, 46]\n18->[1, 4, 5, 7, 9, 41, 44, 45, 47]\n19->[0, 1, 5, 6, 7, 8, 9, 40, 41, 45, 46, 47]\n20->[0, 1, 2, 8, 9, 10, 14, 40, 41, 42]\n21->[0, 2, 3, 8, 10, 11, 14, 15, 40, 42, 43]\n22->[3, 11, 12, 13, 15, 43]\n23->[2, 3, 10, 11, 12, 14, 15, 42, 43]\n24->[4, 5, 32, 33, 35, 36, 37, 44, 45]\n25->[4, 32, 34, 35, 36, 44]\n26->[4, 5, 7, 32, 33, 36, 37, 39, 44, 45, 47]\n27->[5, 6, 7, 33, 37, 38, 39, 45, 46, 47]\n28->[0, 1, 2, 6, 7, 38, 39, 40, 41, 42, 46, 47]\n29->[0, 2, 3, 6, 38, 40, 42, 43, 46]\n30->[1, 4, 5, 7, 36, 37, 39, 41, 44, 45, 47]\n31->[0, 1, 5, 6, 7, 37, 38, 39, 40, 41, 45, 46, 47]\n32->[0, 1, 2, 6, 7, 8, 9, 10, 24, 25, 26]\n33->[0, 2, 3, 6, 8, 10, 11, 24, 26, 27]\n34->[1, 4, 5, 7, 9, 25]\n35->[0, 1, 5, 6, 7, 8, 9, 24, 25]\n36->[0, 1, 2, 8, 9, 10, 14, 24, 25, 26, 30]\n37->[0, 2, 3, 8, 10, 11, 14, 15, 24, 26, 27, 30, 31]\n38->[3, 11, 12, 13, 15, 27, 28, 29, 31]\n39->[2, 3, 10, 11, 12, 14, 15, 26, 27, 28, 30, 31]\n40->[12, 13, 15, 16, 17, 19, 20, 21, 28, 29, 31]\n41->[12, 14, 15, 16, 18, 19, 20, 28, 30, 31]\n42->[12, 13, 16, 17, 20, 21, 23, 28, 29]\n43->[13, 17, 21, 22, 23, 29]\n44->[8, 9, 10, 14, 18, 24, 25, 26, 30]\n45->[8, 10, 11, 14, 15, 18, 19, 24, 26, 27, 30, 31]\n46->[11, 12, 13, 15, 16, 17, 19, 27, 28, 29, 31]\n47->[10, 11, 12, 14, 15, 16, 18, 19, 26, 27, 28, 30, 31]\nif in first column we put-------> second column we put\n01010(0 index in adj)------>10101(16th index) and so on.....\n```\n\nthen do dfs\n ```\nstatic int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n```\n\n\n\ni think it is pretty clear so\n** PLS UPVOTE TO MOTIVATE ME**
1
0
['Dynamic Programming', 'Depth-First Search', 'Java']
0
painting-a-grid-with-three-different-colors
Python | Easier to Understand
python-easier-to-understand-by-aryonbe-3h9n
Foward implementation based on\nhttps://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1330889/Python-O(2mnm)-dp-solution-explained\n
aryonbe
NORMAL
2022-03-18T01:52:10.707249+00:00
2022-04-23T13:06:30.154911+00:00
391
false
Foward implementation based on\nhttps://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1330889/Python-O(2m*n*m)-dp-solution-explained\n\n```\nfrom functools import lru_cache\n#dfs(i,row) means the number of color configuration based on current configuration of upper part(row)\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n MN = m*n\n M = 10**9+7\n @lru_cache(None)\n def dfs(i, row):\n if i == MN:\n return 1\n r, c = divmod(i, m)\n res, feasible_colors = 0, {0, 1, 2}\n if r > 0: feasible_colors.discard(row[0])\n if c > 0: feasible_colors.discard(row[-1])\n for color in feasible_colors:\n res += dfs(i+1,row[1:]+(color,))\n return res%M\n return dfs(0, tuple([3]*m))\n```
1
0
['Depth-First Search', 'Python']
1
painting-a-grid-with-three-different-colors
[C++] hash map for DP with bitmasking column index and colored column, explained
c-hash-map-for-dp-with-bitmasking-column-rlch
The idea is to use 0b100, 0b010 and 0b001 respectively for R, G and B colors. For example, a column of size m = 5 with RGRBG code would give an integer : 0b100
sjaubain
NORMAL
2021-11-21T13:59:53.134636+00:00
2021-11-21T16:52:41.063430+00:00
388
false
The idea is to use `0b100`, `0b010` and `0b001` respectively for R, G and B colors. For example, a column of size `m = 5` with RGRBG code would give an integer : `0b100 010 100 010 001`. To know in one pass how to spot the right column with its index, I shift the index beyond the 32 first bits used for the colors. There are two steps :\n* First I precompute all the valid colors that I store in a vector.\n* Then I perform a DFS from each one of those colors and stop the recursion as soon as the previous column was already obtained so far, looking in the DP data structure. the DP gives for a certain pair (column, index) the number of solutions that start from that colored column at that column index.\n```\nclass Solution {\npublic:\n int colorTheGrid(int m, int n) {\n \n unordered_map<long, int> dp; \n vector<int> validCols; \n \n generateCols(m, validCols, 0, 0);\n \n return getNbSols(validCols, 0, 0, n, dp);\n }\n \n /**\n * compute the number of valid solutions for the grid, performing a DFS\n * from each of the precomputed valid colors (3 * 2 ^ (m - 1) possible permutations).\n * Use the hash map to reuse the dynamically computed solutions.\n */\n int getNbSols(vector<int>& validCols, int prevCol, long colIdx, int n, unordered_map<long, int>& dp) {\n if(colIdx == n) return 1;\n int ans = 0;\n for(int col : validCols) {\n if(not (col & prevCol)) { // check horizontal crossing, not processing adjacent colors\n if(dp.find((colIdx << 32) + col) == dp.end()) {\n dp[(colIdx << 32) + col] = getNbSols(validCols, col, colIdx + 1, n, dp); \n }\n ans = (ans + dp[(colIdx << 32) + col]) % MOD;\n }\n }\n return ans % MOD;\n }\n \n /**\n * generate all valid color permutations for a column, i.e those who\n * does not have two same adjacent colors\n */\n void generateCols(int m, vector<int>& validCols, int curCol, int rowIdx) {\n if(rowIdx == m) {validCols.push_back(curCol); return;}\n for(int c = 0b001; c <= 0b100; c *= 2) {\n int prev_c = 0;\n if(rowIdx) prev_c = curCol >> 3 * (rowIdx - 1) & 0b111;\n if(prev_c != c) { // check vertical crossing, not processing adjacent colors\n generateCols(m, validCols, c << 3 * rowIdx | curCol, rowIdx + 1);\n }\n }\n }\n\nprivate:\n int MOD = 1e9 + 7;\n};\n```
1
0
['C']
0
painting-a-grid-with-three-different-colors
(C++) 1931. Painting a Grid With Three Different Colors
c-1931-painting-a-grid-with-three-differ-33j8
\n\nclass Solution {\npublic:\n int colorTheGrid(int m, int n) {\n long memo[m][n][1<<2*m]; \n memset(memo, 0, sizeof(memo));\n \n
qeetcode
NORMAL
2021-07-15T15:45:14.998261+00:00
2021-07-15T15:45:47.075517+00:00
524
false
\n```\nclass Solution {\npublic:\n int colorTheGrid(int m, int n) {\n long memo[m][n][1<<2*m]; \n memset(memo, 0, sizeof(memo));\n \n function<long(int, int, int)> fn = [&](int i, int j, int mask) {\n if (j == n) return 1l; \n if (i == m) return fn(0, j+1, mask); \n if (!memo[i][j][mask]) \n for (const int& x : {1<<(2*i), 1<<(2*i+1), 3<<(2*i)}) {\n int mask0 = mask ^ x; \n if ((mask0 & 3<<2*i) != 0 && (i == 0 || (mask0>>2*i & 3) != (mask0>>2*i-2 & 3))) {\n memo[i][j][mask] = (memo[i][j][mask] + fn(i+1, j, mask0)) % 1\'000\'000\'007; \n }\n }\n return memo[i][j][mask]; \n };\n \n return fn(0, 0, 0); \n }\n};\n```
1
0
['C']
0
painting-a-grid-with-three-different-colors
[Python3] top-down dp
python3-top-down-dp-by-ye15-zt4s
\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \n @cache\n def fn(i, j, mask): \n """Return number of
ye15
NORMAL
2021-07-15T04:13:40.416042+00:00
2021-07-15T04:13:40.416068+00:00
462
false
\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \n @cache\n def fn(i, j, mask): \n """Return number of ways to color grid."""\n if j == n: return 1 \n if i == m: return fn(0, j+1, mask)\n ans = 0 \n for x in 1<<2*i, 1<<2*i+1, 0b11<<2*i: \n mask0 = mask ^ x\n if mask0 & 0b11<<2*i and (i == 0 or (mask0 >> 2*i) & 0b11 != (mask0 >> 2*i-2) & 0b11): \n ans += fn(i+1, j, mask0)\n return ans % 1_000_000_007\n \n return fn(0, 0, 0)\n```
1
0
['Python3']
2
painting-a-grid-with-three-different-colors
Mutation from hiepit's 3 X N solution
mutation-from-hiepits-3-x-n-solution-by-ysnhe
I know this solution looks a bit silly but understandable and feasible!\nMutate from : https://leetcode.com/problems/painting-a-grid-with-three-different-colors
GoogleNick
NORMAL
2021-07-12T18:00:07.848687+00:00
2021-07-12T18:14:41.445392+00:00
103
false
I know this solution looks a bit silly but understandable and feasible!\nMutate from : https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1330185/C%2B%2BPython-DP-and-DFS-and-Bitmask-Picture-explain-Clean-and-Concise\n```\nclass Solution {\n int dp[1001][4][4][4][4][4] = {};\npublic:\n int colorTheGrid(int m, int n) {\n vector<int> colors = {1,2,3};\n return dfs(n,0,0,0,0,0,colors,m);\n }\n int dfs(int n, int a0, int b0, int c0,int d0,int e0, const vector<int> &colors,int &m){\n if(n == 0) return 1;\n if(dp[n][a0][b0][c0][d0][e0] > 0) return dp[n][a0][b0][c0][d0][e0];\n int res = 0;\n for(int a : colors){\n if(a == a0) continue;\n if(m==1) {res += dfs(n-1,a,0,0,0,0,colors,m);res %= 1000000007;}\n else{\n for(int b : colors){\n if(b == a || b == b0) continue;\n if(m==2) {res += dfs(n-1,a,b,0,0,0,colors,m); res %= 1000000007;}\n else{\n for(int c : colors){\n if(c == b || c == c0) continue;\n if(m==3) {res += dfs(n-1,a,b,c,0,0,colors,m); res %= 1000000007;}\n else{\n for(int d : colors){\n if(d == c || d == d0) continue;\n if(m==4) {res += dfs(n-1,a,b,c,d,0,colors,m);res %= 1000000007;}\n else{\n for(int e : colors){\n if(e == d || e == e0) continue;\n res+= dfs(n-1,a,b,c,d,e,colors,m);res %= 1000000007;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return dp[n][a0][b0][c0][d0][e0] = res;\n }\n};\n```
1
0
[]
1
painting-a-grid-with-three-different-colors
[Javascript] Bitmask & DFS with Cache
javascript-bitmask-dfs-with-cache-by-zac-c2c8
Javascript version of - https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1330185/C%2B%2BPython-DP-and-DFS-and-Bitmask-Picture-e
zachzwy
NORMAL
2021-07-11T23:38:53.148775+00:00
2021-07-11T23:38:53.148806+00:00
103
false
Javascript version of - https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1330185/C%2B%2BPython-DP-and-DFS-and-Bitmask-Picture-explain-Clean-and-Concise\n\n```\n// To store previous column state in DP, we can use BitMask,\n// each 2 bits store a color (1=Red, 2=Green, 3=Blue, 0=White),\n// so there is total 4^M column states.\nvar colorTheGrid = function (m, n) {\n // Generate all possible columns we can draw, if the previous col is \'prevColMask\'\n const getNextState = (prevState) => {\n // Get color of the \'state\' at \'pos\', use 2 bits to store a color\n const getColor = (state, pos) => (state >> (2 * pos)) & 3;\n // Set \'color\' to the \'state\' at \'pos\', use 2 bits to store a color\n const setColor = (state, pos, color) => state | (color << (2 * pos));\n const res = [];\n const helper = (row, curState, prevState) => {\n // Fill all color for this column\n if (row === m) {\n res.push(curState);\n return;\n }\n // Try colors i in [1=RED, 2=GREEN, 3=BLUE]\n for (let i = 1; i <= 3; i++) {\n if (\n getColor(prevState, row) !== i &&\n (row === 0 || getColor(curState, row - 1) !== i)\n )\n helper(row + 1, setColor(curState, row, i), prevState);\n }\n };\n helper(0, 0, prevState);\n return res;\n };\n\n const dp = Array.from(Array(n), () => Array(4 ** m));\n\n const dfs = (col = 0, prevState = 0) => {\n if (col === n) return 1;\n if (dp[col][prevState]) return dp[col][prevState];\n let res = 0;\n for (const nextState of getNextState(prevState)) {\n res = (res + dfs(col + 1, nextState)) % (10 ** 9 + 7);\n }\n return (dp[col][prevState] = res);\n };\n\n return dfs();\n};\n```
1
0
[]
0
painting-a-grid-with-three-different-colors
1931 Backtrack with memo | DP row by row
1931-backtrack-with-memo-dp-row-by-row-b-ajvr
Solution 1: simple backtrack\n2D dp -> 1D dp -> string (string is hashable(cached) while list is not)\nm is no more than 5, so let m be 1D dp dimension\n\ndef c
m1kasa
NORMAL
2021-07-11T14:24:14.912473+00:00
2021-07-23T03:46:07.584271+00:00
177
false
# Solution 1: simple backtrack\n2D dp -> 1D dp -> string (string is hashable(cached) while list is not)\nm is no more than 5, so let m be 1D dp dimension\n```\ndef colorTheGrid(self, m: int, n: int) -> int:\n\t@lru_cache(None)\n\tdef backtrack(k=0, dp="0" * (m + 1)):\n\t\tif k == m * n: return 1\n\t\ti, j = divmod(k, m)\n\t\tres = 0\n\t\tfor color in {"1", "2", "3"} - {dp[j], dp[j-1]}:\n\t\t\tnew_dp = dp[:j] + color + dp[j+1:]\n\t\t\tres += backtrack(k+1, new_dp)\n\t\t\tres %= 10**9 + 7\n\t\treturn res\n\n\treturn backtrack()\n```\nimplement cache myself\n```\ndef colorTheGrid(self, m: int, n: int) -> int:\n cache = {}\n def backtrack(k=0, dp="0" * (m + 1)):\n if (k, dp) not in cache:\n if k == m * n: return 1\n i, j = divmod(k, m)\n res = 0\n for color in {"1", "2", "3"} - {dp[j], dp[j-1]}:\n new_dp = dp[:j] + color + dp[j+1:]\n res += backtrack(k+1, new_dp)\n res %= 10**9 + 7\n cache[(k, dp)] = res\n return cache[(k, dp)]\n\n return backtrack()\n```\n# Solution 2: DP\n```\ndef colorTheGrid(self, m: int, n: int) -> int:\n def backtrack(pre, i=0, cur=["0"]*(m+1), curs=set()):\n # input: color pattern of the previous row\n # output: set of possible color patterns of the current row\n if i == m: return curs.add("".join(cur))\n for color in {"1", "2", "3"} - {pre[i], cur[i-1]}:\n cur[i] = color\n backtrack(pre, i+1, cur, curs)\n\n cache = collections.defaultdict(set) # to better the backtrack above\n pre_dp = {"0"*(m+1): 1} # possible color patterns of previous row with counts\n for _ in range(n):\n dp = collections.defaultdict(int)\n for pre, cnt in pre_dp.items():\n if pre not in cache:\n backtrack(pre, curs=cache[pre])\n for cur in cache[pre]:\n dp[cur] += cnt\n dp[cur] %= 10**9 + 7\n pre_dp = dp\n return sum(pre_dp.values()) % (10**9 + 7)\n```\n\n
1
0
[]
0
painting-a-grid-with-three-different-colors
[Python] Faster then 100%
python-faster-then-100-by-whymustihavean-aw6j
The mats are the transition matrices I calculated using other codes.\n\n\nimport numpy\nmats=[None,None,None,numpy.array([[3, 2], [2, 2]]),\n numpy.array([[3
WhymustIhaveaname
NORMAL
2021-07-11T05:45:07.174977+00:00
2021-07-11T05:45:07.175044+00:00
138
false
The `mats` are the transition matrices I calculated using other codes.\n\n```\nimport numpy\nmats=[None,None,None,numpy.array([[3, 2], [2, 2]]),\n numpy.array([[3, 2, 1, 2], [2, 2, 1, 2], [1, 1, 2, 1], [2, 2, 1, 2]]),\n numpy.array([[3, 2, 2, 1, 0, 1, 2, 2], [2, 2, 2, 1, 1, 1, 1, 1], [2, 2, 2, 1, 0, 1, 2, 2], [1, 1, 1, 2, 1, 1, 1, 1], [0, 1, 0, 1, 2, 1, 0, 1], [1, 1, 1, 1, 1, 2, 1, 1], [2, 1, 2, 1, 0, 1, 2, 1], [2, 1, 2, 1, 1, 1, 1, 2]])]\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n if m==1:\n return int(6*2**(n-2))%(1000000007)\n elif m==2:\n return 6*int(3**(n-1))%(1000000007)\n mat=mats[m]\n v=numpy.array([1 for i in range(len(mat))])\n for i in range(n-1):\n v=numpy.array([j%1000000007 for j in mat.dot(v)])\n return 6*sum(v)%1000000007\n```
1
0
['Dynamic Programming', 'Matrix']
1
painting-a-grid-with-three-different-colors
[Python3] Dynamic Programming Explained | O(mn(3^ m))
python3-dynamic-programming-explained-om-h971
Approach\n\nWe have a grid of size ( m * n ) and we want to fill each grid box with some color with 3 choices. A look at constraints gives some insight on numbe
wormx
NORMAL
2021-07-11T04:45:34.960072+00:00
2021-07-11T04:53:36.521274+00:00
133
false
Approach\n\nWe have a grid of size ( m * n ) and we want to fill each grid box with some color with 3 choices. A look at constraints gives some insight on number of rows being limited to 5 which seems to be a good candidate for a ternary mask (base 3).\n\nLets try to explain this with an exmaple.\nAsume m = 3 and n = 3\n\n```\ninitial state: grid\n. . .\n. . .\n. . .\n\ninitial state: previous column fills [-1 , -1 , -1]\n\nLets assume , we fill top to bottom (column 0) in following manner color 0 , then color 1 then color 2\n\n 0 . .\n 1 . .\n 2 . .\n\nnow column 0 is all filled and we want to start filling column 1\n```\nwe are at index (0 , 1)\nwe are now interested in information on left of it , i.e. same row previous cloumn \nand also interested in information on top of it i.e same column previous row\n**Note only these two cells are ever needed to fill the ongoing box**\n\nOne way of doing it could be to store the **previous** column state in a ternary mask\n\n(Instead of using a ternary mask i am using a tuple of size m (max : 5) which will basically store values in range of [0 , 1 , 2] to give me information on what all colors were filled in the row index of previous column. there is a special value -1 which indicates there was no paint on previous column as its out of boundary (true only for first column))\n\n\nI hope till this point you understand that to start working on partiular column, you need fill information on previous column.\nThe most challenging part of this problem is to prepare the fill state ( mask ) for next column in an optimal way\n\nIts more initutive to explain the preparation part with help of an example\n\n```\n\n0 . .\n1 . .\n2 . .\n\nlets say after some fills on cloumn 1 state of column1 is like\n\n0 2 .\n1 0 .\n2 1 .\n\nNow how to get this information [2 , 0 ,1 ] available for column index 2 ? for matter of fact, same question applies on how to get [0 , 1 , 2 ] information available to column index 1\n\nThe idea is to modify the mask we are presented with to begin the iteration. lets see how\n\n* denotes current cell to find a fill\n\n0 * .\n1 . .\n2 . .\n\nyou can fill this cell with color 1 or 2, lets fill 2 and store this information in ongoing mask at index 0\n\n2 f .\n1 . .\n2 . .\n\nNote f denotes the cell is filled but we have modified the existing mask instead of creating a new one for this column\n\nthe next index to fill is (1 , 1)\n\n2 f .\n1 * .\n2 . .\n\nit needs infomration for the left cell and top cell. If the idea has not sparked yet, let me help you. the left value is still not modified (1) and top value can be obtained from the cell above it (2) which we modifed at previous step\n\nfill this with color 0 and modify mask to 0 \n\n2 f .\n0 f .\n2 * .\n\nfor the next index (2 , 1) top and left values are 0 and 2 respectively. lets fill it with 1 \n\n2 f .\n0 f .\n1 f .\n\nin this way you modified the existing mask and prepared it to fill the next column\n```\n\n\nThe rest code is simple DFS based DP that if you are comfortable with it should not be hard to follow. Do let me know in comments if you want explaination in any certain part of the code\n\nThanks for reading\n\n\n\nHere is the code for your perusal\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \n init = tuple([-1]*m)\n mod = 10**9 + 7\n \n @lru_cache(None)\n def solve(i , j , fill):\n if j == n:\n return 1\n \n state = list(fill)\n \n if i == m-1:\n ans = 0\n v1 = state[i]\n v2 = state[i-1] if i else -1\n \n for paint in [0 , 1 , 2]:\n if paint != v1 and paint != v2:\n state[i] = paint\n ans += solve(0 , j+1 , tuple(state))\n ans %= mod\n \n return ans%mod\n else:\n ans = 0\n v1 = state[i]\n v2 = -1 if not i else state[i-1]\n \n for paint in [0 , 1 , 2]:\n if paint != v1 and paint != v2:\n state[i] = paint\n ans += solve(i+1 , j ,tuple(state))\n ans %= mod\n \n return ans%mod\n \n \n return solve(0 , 0 , init)%mod\n \n```
1
0
[]
0
painting-a-grid-with-three-different-colors
[Python] Column-by-Column Counting
python-column-by-column-counting-by-nthi-5gbg
The general idea of this approach is that since columns are small, m <= 5, we can think about counting the number of ways as we fill out the grid left to right,
nthistle
NORMAL
2021-07-11T04:30:07.444477+00:00
2021-07-11T04:30:07.444541+00:00
210
false
The general idea of this approach is that since columns are small, `m <= 5`, we can think about counting the number of ways as we fill out the grid left to right, column by column. Specifically, once we fill out a column, we no longer care about the colors in any other columns to the left of it. This way, we can just keep track of how many colorings there are that "end" in a specific column coloring. When we want to add another column (move "right"), we simply figure out which column-colorings are valid from each current column-coloring, and then update.\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n valid = []\n for r in itertools.product(*[(0,1,2) for _ in range(m)]):\n if all(r[i] != r[i+1] for i in range(m-1)):\n valid.append(r)\n g = {i:set() for i in range(len(valid))}\n for i in range(len(valid)):\n for j in range(i+1,len(valid)):\n if all(valid[i][x] != valid[j][x] for x in range(m)):\n g[i].add(j)\n g[j].add(i)\n s=[1 for _ in range(len(valid))]\n for _ in range(n-1):\n ns=[0 for _ in range(len(valid))]\n for i in range(len(valid)):\n for j in g[i]:\n ns[j] = (ns[j] + s[i]) % 1000000007\n s=ns\n return sum(s) % 1000000007\n```\nThis only works because m is small: at m=5, there\'s only 48 valid column-colorings, which means 48<sup>2</sup> = 2304 transitions (although it\'s smaller since we preprocess it into a "graph", where an edge between two column-colorings indicates that they can be adjacent to each other), which we only need to repeat n<=1000 times.\n\nAfter that we just sum up the number of valid colorings ending in each configuration and we have our answer. The efficiency of this approach is bounded by O(n * 3<sup>2m</sup>) ~ 59M ops here, but in practice it\'s faster because there are significantly fewer than 3^m valid column-colorings, and the preprocessed graph isn\'t too dense.
1
0
[]
0
painting-a-grid-with-three-different-colors
C++| Brute way | using strings for state
c-brute-way-using-strings-for-state-by-a-cy9g
```\nclass Solution {\npublic:\n void g(string &s,int m,vector&v,int i,string &c){\n if(i==m){\n v.push_back(c);\n return;\n
amar_o1
NORMAL
2021-07-11T04:12:26.859673+00:00
2021-07-11T04:12:26.859706+00:00
189
false
```\nclass Solution {\npublic:\n void g(string &s,int m,vector<string>&v,int i,string &c){\n if(i==m){\n v.push_back(c);\n return;\n }\n if(i==0){\n for(int j=1;j<=3;j++){\n if(j!=s[i]-\'0\'){\n c.push_back(j+\'0\');\n g(s,m,v,i+1,c);\n c.pop_back();\n }\n }\n }else{\n for(int j=1;j<=3;j++){\n if(j!=s[i]-\'0\' && j!=c[i-1]-\'0\'){\n c.push_back(j+\'0\');\n g(s,m,v,i+1,c);\n c.pop_back();\n }\n }\n }\n }\n unordered_map<string,int>ma;\n unordered_map<string,vector<string>>store;\n int mod = 1e9+7;\n int f(int n,int m,string s,int i){\n if(i==n)return 1;\n string mm = s + "-" + to_string(i);\n if(ma.count(mm))return ma[mm];\n string ss="";\n int ans=0;\n if(store.count(s)){\n for(auto x:store[s]){ \n ans = (ans%mod + f(n,m,x,i+1)%mod)%mod;\n }\n }\n else{\n vector<string> v;\n g(s,m,v,0,ss);\n store[s] = v;\n for(auto x:v){ \n ans = (ans%mod + f(n,m,x,i+1)%mod)%mod;\n }\n }\n return ma[mm] = ans;\n }\n int colorTheGrid(int m, int n) {\n string s = "";\n for(int i=0;i<m;i++)s.push_back(\'0\');\n return f(n,m,s,0);\n }\n};
1
1
[]
0
painting-a-grid-with-three-different-colors
Python 3 dp
python-3-dp-by-szlghl1-06o4
python\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n endings = set()\n \n def dfs_ending(i, cur_ending):\n
szlghl1
NORMAL
2021-07-11T04:01:15.686228+00:00
2021-07-11T04:01:15.686257+00:00
441
false
```python\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n endings = set()\n \n def dfs_ending(i, cur_ending):\n if i == m:\n endings.add(cur_ending)\n return\n for to_add in range(3):\n c = str(to_add)\n if cur_ending and cur_ending[-1] == c:\n continue\n dfs_ending(i + 1, cur_ending + c)\n dfs_ending(0, \'\')\n MOD = 10 ** 9 + 7\n dp = [defaultdict(int) for _ in range(2)]\n for ending in endings:\n dp[1][ending] = 1\n \n def compatible(e1, e2):\n for i in range(len(e1)):\n if e1[i] == e2[i]:\n return False\n return True\n \n for i in range(2, n + 1):\n dp[i % 2] = defaultdict(int)\n for prev_ending, prev_count in dp[(i-1) % 2].items():\n for ending in endings:\n if compatible(prev_ending, ending):\n dp[i % 2][ending] += prev_count\n dp[i % 2][ending] %= MOD\n res = 0\n for v in dp[n % 2].values():\n res += v\n res %= MOD\n return res\n```
1
1
[]
2
painting-a-grid-with-three-different-colors
1931. Painting a Grid With Three Different Colors
1931-painting-a-grid-with-three-differen-fcau
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-16T12:43:08.697235+00:00
2025-01-16T12:43:08.697235+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { private static final int MODULO = 1_000_000_007; public int colorTheGrid(int rows, int cols) { Map<Integer, Long> stateCount = new HashMap<>(); createValidStates(stateCount, 0, rows, 0, 0); for (int col = 1; col < cols; col++) { Map<Integer, Long> newStateCount = new HashMap<>(); for (int currentState : stateCount.keySet()) { for (int nextState : stateCount.keySet()) { if ((currentState & nextState) == 0) { newStateCount.put( nextState, (newStateCount.getOrDefault(nextState, 0L) + stateCount.get(currentState)) % MODULO ); } } } stateCount = newStateCount; } long totalWays = 0; for (long count : stateCount.values()) { totalWays = (totalWays + count) % MODULO; } return (int) totalWays; } private void createValidStates(Map<Integer, Long> stateCount, int position, int totalRows, int previousColor, int currentState) { if (position == totalRows) { stateCount.put(currentState, stateCount.getOrDefault(currentState, 0L) + 1); return; } for (int color = 1; color <= 3; color++) { if (color != previousColor) { createValidStates(stateCount, position + 1, totalRows, color, (currentState << 3) | (1 << color)); } } } } ```
0
0
['Java']
0
painting-a-grid-with-three-different-colors
DP java
dp-java-by-garcol-0ju7
IntuitionDPApproachBitmask to store previous stateComplexity Time complexity: 243 * O(n) Space complexity: 243 * O(n) Code
garcol
NORMAL
2025-01-14T14:31:09.120680+00:00
2025-01-14T14:55:23.602638+00:00
15
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> DP # Approach <!-- Describe your approach to solving the problem. --> Bitmask to store previous state # Complexity - Time complexity: 243 * O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: 243 * O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { final int RED = 0; final int GREEN = 1; final int BLUE = 2; final int TOTAL_COLOR = 3; int maxColumn; int maxRow; int MOD = 1_000_000_007; Map<Integer, Map<Integer, Long>> memoi = new HashMap<>(); /** * time complexity: (3 ^ m) * O(n) * @param m 1 <= m <= 5 * @param n 1 <= n <= 1000 */ public int colorTheGrid(int m, int n) { maxRow = m; maxColumn = n; return (int) dp(-1, 0); } long dp(int previousColumnTotalValue, int columnIndex) { if (columnIndex == maxColumn) return 1; Long memoiValue = Optional.ofNullable(memoi.get(previousColumnTotalValue)).map(map -> map.get(columnIndex)).orElse(null); if (memoiValue != null) { return memoiValue; } List<Integer> availableColumns = new ArrayList<>(); buildColumns(previousColumnTotalValue, 0, -1, 0, availableColumns); Long currentValue = availableColumns.stream() .map(columnTotalValue -> dp(columnTotalValue, columnIndex + 1) % MOD) .reduce(Long::sum) .map(value -> value % MOD) .orElse(0L); memoi.computeIfAbsent(previousColumnTotalValue, (key) -> new HashMap<>()).put(columnIndex, currentValue); return currentValue; } void buildColumns(int previousColumnTotalValue, int currentColumnValue, int previousRowColor, int rowIndex, List<Integer> columnsValues) { if (rowIndex == maxRow) { columnsValues.add(currentColumnValue); return; } for (int color = RED; color < TOTAL_COLOR; color++) { if (previousColumnTotalValue != -1) { int previousColumnColor = getColorAt(previousColumnTotalValue, rowIndex); if (color == previousColumnColor) continue; } if (rowIndex > 0 && color == previousRowColor) continue; int newColValue = pushColor(currentColumnValue, color, rowIndex); buildColumns(previousColumnTotalValue, newColValue, color, rowIndex + 1, columnsValues); } } /** * * @param color { red: 0, green: 1, blue: 2 } * @return new column value */ public int pushColor(int currentColumnValue, int color, int rowIndex) { return currentColumnValue + color * (int) Math.pow(TOTAL_COLOR, rowIndex); } public int getColorAt(int columnValue, int rowIndex) { return (columnValue / ((int) Math.pow(TOTAL_COLOR, rowIndex))) % TOTAL_COLOR; } } ```
0
0
['Java']
0
painting-a-grid-with-three-different-colors
dp+ cache
dp-cache-by-akther-dpg2
IntuitionApproachComplexity Time complexity: Space complexity: Code
akther
NORMAL
2025-01-07T11:53:26.942059+00:00
2025-01-07T11:53:26.942059+00:00
14
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def colorTheGrid(self, m, n): # Initialize the cache cache = {} def dp(seq, lastRow): if seq == m * n: return 1 if (seq, lastRow) in cache: return cache[(seq, lastRow)] i = seq // m j = seq % m lastRowList = list(lastRow) ans = 0 neighborColors = set() if i > 0: neighborColors.add(lastRowList[j]) if j > 0: neighborColors.add(lastRowList[j - 1]) for c in (0, 1, 2): if c not in neighborColors: newLastRow = lastRowList[:] newLastRow[j] = c ans += dp(seq + 1, tuple(newLastRow)) ans = ans % mod cache[(seq, lastRow)] = ans # Cache the result return ans mod = 10**9 + 7 return dp(0, tuple([0] * m)) ```
0
0
['Dynamic Programming', 'Python3']
0
painting-a-grid-with-three-different-colors
Make DAG of adjacent rows
make-dag-of-adjacent-rows-by-theabbie-fxsa
\nM = 10 ** 9 + 7\n\ncache = {}\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n if m not in cache:\n good = []\n
theabbie
NORMAL
2024-12-27T06:59:45.496781+00:00
2024-12-27T06:59:45.496805+00:00
4
false
```\nM = 10 ** 9 + 7\n\ncache = {}\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n if m not in cache:\n good = []\n def gen(arr):\n if len(arr) == m:\n good.append(arr[:])\n return\n for l in range(3):\n if arr and l == arr[-1]:\n continue\n arr.append(l)\n gen(arr)\n arr.pop()\n gen([])\n edges = [[] for _ in range(len(good))]\n g = len(good)\n for i in range(g):\n for j in range(g):\n valid = True\n for k in range(m):\n if good[i][k] == good[j][k]:\n valid = False\n break\n if valid:\n edges[i].append(j)\n cache[m] = edges\n edges = cache[m]\n g = len(edges)\n dp = [1] * g\n ndp = [0] * g\n for _ in range(1, n):\n for i in range(g):\n ndp[i] = 0\n for j in edges[i]:\n ndp[i] += dp[j]\n ndp[i] %= M\n dp, ndp = ndp, dp\n return sum(dp) % M\n```
0
0
['Python']
0
painting-a-grid-with-three-different-colors
1931. Painting a Grid With Three Different Colors.cpp
1931-painting-a-grid-with-three-differen-x4ij
Code\n\nclass Solution {\npublic:\n int colorTheGrid(int m, int n) {\n long memo[m][n][1<<2*m]; \n memset(memo, 0, sizeof(memo));\n \n
202021ganesh
NORMAL
2024-10-22T09:51:40.868931+00:00
2024-10-22T09:51:40.868972+00:00
3
false
**Code**\n```\nclass Solution {\npublic:\n int colorTheGrid(int m, int n) {\n long memo[m][n][1<<2*m]; \n memset(memo, 0, sizeof(memo));\n \n function<long(int, int, int)> fn = [&](int i, int j, int mask) {\n if (j == n) return 1l; \n if (i == m) return fn(0, j+1, mask); \n if (!memo[i][j][mask]) \n for (const int& x : {1<<(2*i), 1<<(2*i+1), 3<<(2*i)}) {\n int mask0 = mask ^ x; \n if ((mask0 & 3<<2*i) != 0 && (i == 0 || (mask0>>2*i & 3) != (mask0>>2*i-2 & 3))) {\n memo[i][j][mask] = (memo[i][j][mask] + fn(i+1, j, mask0)) % 1\'000\'000\'007; \n }\n }\n return memo[i][j][mask]; \n };\n \n return fn(0, 0, 0); \n }\n};\n```
0
0
['C']
0
painting-a-grid-with-three-different-colors
Painting a Grid With Three Different Colors
painting-a-grid-with-three-different-col-ifsc
\n# Approach\n Describe your approach to solving the problem. \nGenerate Valid Row Configurations:\n\nEnumerate all possible ways to color a single row of lengt
Ansh1707
NORMAL
2024-10-15T07:52:12.108108+00:00
2024-10-15T07:52:12.108133+00:00
6
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGenerate Valid Row Configurations:\n\nEnumerate all possible ways to color a single row of length \n\uD835\uDC5A\nm with three colors while ensuring that no two adjacent cells share the same color.\nDetermine Valid Transitions Between Rows:\n\nPrecompute which row configurations can follow another row configuration without violating the adjacent coloring constraints.\nDynamic Programming Table Setup:\n\nLet dp[j][config] represent the number of ways to color the grid up to column j, ending with row configuration config.\nTransition from column j to j+1 based on valid row configurations.\nModulo Arithmetic:\n\nSince the result can be large, use modulo 10^9+7 for the calculations.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nGenerating Valid Rows: O(3^m), where 3^m is the number of potential configurations.\n\nTransition Checking: O(3^m . 3^m . m)\n\nDynamic Programming Filling: (n . 3^m . 3^m)).\n\n# Code\n```python []\nclass Solution(object):\n def colorTheGrid(self, m, n):\n """\n :type m: int\n :type n: int\n :rtype: int\n """\n MOD = 10**9 + 7\n \n # Helper function to generate all valid row configurations\n def generate_valid_rows(m):\n colors = [0, 1, 2] # 0: red, 1: green, 2: blue\n valid_rows = []\n \n def backtrack(row):\n if len(row) == m:\n valid_rows.append(tuple(row))\n return\n for color in colors:\n if not row or row[-1] != color: # Ensure no two adjacent cells are the same\n row.append(color)\n backtrack(row)\n row.pop()\n \n backtrack([])\n return valid_rows\n \n # Generate all valid row configurations for m\n valid_rows = generate_valid_rows(m)\n num_configs = len(valid_rows)\n \n # Precompute transitions between row configurations\n transitions = [[] for _ in range(num_configs)]\n for i in range(num_configs):\n for j in range(num_configs):\n # Check if row i can transition to row j\n if all(valid_rows[i][k] != valid_rows[j][k] for k in range(m)):\n transitions[i].append(j)\n \n # Initialize the DP table\n dp = [[0] * num_configs for _ in range(n)]\n \n # Base case: first column can be any valid configuration\n for i in range(num_configs):\n dp[0][i] = 1\n \n # Fill the DP table\n for j in range(1, n):\n for i in range(num_configs):\n for prev in transitions[i]:\n dp[j][i] = (dp[j][i] + dp[j-1][prev]) % MOD\n \n # Sum all ways to color the grid up to column n-1\n result = sum(dp[n-1][i] for i in range(num_configs)) % MOD\n \n return result\n\n```
0
0
['Python']
0
painting-a-grid-with-three-different-colors
USING GRAPHS BUT GETTING TIME LIMIT EXCEEDED.
using-graphs-but-getting-time-limit-exce-ia13
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
damon109
NORMAL
2024-08-19T21:46:25.691029+00:00
2024-08-19T21:46:25.691053+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int mod=1e9+7;\n\n void csc(vector<string> &v, int m, int i, string s) {\n // Base Case: if we have formed a string of length m, we add it to the list and return\n if (i == m) {\n v.push_back(s);\n return;\n }\n \n // Ensure we are not adding the same character consecutively\n if (i == 0 || s[i-1] != \'0\') {\n csc(v, m, i + 1, s + \'0\');\n }\n if (i == 0 || s[i-1] != \'1\') {\n csc(v, m, i + 1, s + \'1\');\n }\n if (i == 0 || s[i-1] != \'2\') {\n csc(v, m, i + 1, s + \'2\');\n }\n }\n\n void bfs(vector<vector<int>> &v, int src, int parent, int &count, int n, int c) {\n if (c == n) {\n count = (count + 1) % mod;\n return;\n }\n for (int i = 0; i < v[src].size(); ++i) {\n //if (v[src][i] != parent) {\n bfs(v, v[src][i], src, count, n, c + 1);\n //}\n }\n }\n \n int colorTheGrid(int m, int n) {\n vector<string> v;\n string s;\n csc(v, m, 0, s);\n \n int x = v.size();\n vector<vector<int>> adj(x);\n \n for (int i = 0; i < x; ++i) {\n for (int j = i + 1; j < x; ++j) {\n bool b = true;\n for (int k = 0; k < m; ++k) {\n if (v[i][k] == v[j][k]) {\n b = false;\n break;\n }\n }\n if (b) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n }\n\n int count = 0;\n for (int i = 0; i < x; ++i) {\n bfs(adj, i, -1, count, n, 1);\n count = count % mod;\n }\n return count;\n }\n};\n```
0
0
['Dynamic Programming', 'Graph', 'C++']
0
painting-a-grid-with-three-different-colors
BY USING PREDEFINED STRING WITH ADJACENT MATRIX WITH DP.
by-using-predefined-string-with-adjacent-xgbv
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
damon109
NORMAL
2024-08-19T21:40:28.521055+00:00
2024-08-19T21:40:28.521087+00:00
7
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n\n void generateValidRows(vector<string>& validRows, int m, int i, string s) {\n if (i == m) {\n validRows.push_back(s);\n return;\n }\n for (char color = \'0\'; color <= \'2\'; ++color) {\n if (i == 0 || s[i - 1] != color) {\n generateValidRows(validRows, m, i + 1, s + color);\n }\n }\n }\n\n int colorTheGrid(int m, int n) {\n vector<string> validRows;\n generateValidRows(validRows, m, 0, "");\n int rowCount = validRows.size();\n\n // Create adjacency list\n vector<vector<int>> adj(rowCount);\n for (int i = 0; i < rowCount; ++i) {\n for (int j = 0; j < rowCount; ++j) {\n bool canPlace = true;\n for (int k = 0; k < m; ++k) {\n if (validRows[i][k] == validRows[j][k]) {\n canPlace = false;\n break;\n }\n }\n if (canPlace) {\n adj[i].push_back(j);\n }\n }\n }\n\n // dp table to store the number of ways to paint the grid up to the current column\n vector<int> dp(rowCount, 1);\n\n // Fill dp table\n for (int col = 1; col < n; ++col) {\n vector<int> newDp(rowCount, 0);\n for (int i = 0; i < rowCount; ++i) {\n for (int j : adj[i]) {\n newDp[j] = (newDp[j] + dp[i]) % mod;\n }\n }\n dp = newDp;\n }\n\n int count = 0;\n for (int i = 0; i < rowCount; ++i) {\n count = (count + dp[i]) % mod;\n }\n return count;\n }\n};
0
0
['Dynamic Programming', 'C++']
0
painting-a-grid-with-three-different-colors
Bit Masking with easy intuitive variable names
bit-masking-with-easy-intuitive-variable-l5lo
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Dhruv_001
NORMAL
2024-08-06T12:43:26.425247+00:00
2024-08-06T12:43:26.425277+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*3^N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N*3^N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9+7;\n int solveUsingRecursion(int n, int m, vector<vector<int>>& grid, int row, int col){\n if(row == n){\n return 1;\n }\n\n int count = 0;\n vector<int> color(3,0);\n if(col>0) color[grid[row][col-1]] = 1;\n if(row>0) color[grid[row-1][col]] = 1;\n\n for(int c=0;c<3;c++){\n if(color[c] == 0){\n grid[row][col] = c;\n if(col+1 < m){\n count += solveUsingRecursion(n,m,grid,row,col+1)%mod;\n }else{\n count += solveUsingRecursion(n,m,grid,row+1,0)%mod;\n }\n }\n }\n return count%mod;\n }\n\n int solveUsingBitMasking(long long n, long long m, long long row,long long col,long long premask,long long currmask,vector<unordered_map<long long,long long>>& dp){\n if(row == n) return 1;\n if(dp[row].find(premask) != dp[row].end()) return dp[row][premask];\n\n //if we reach end of row, then we will shift to row+1, and return it\'s ans.\n if(col == m){\n return (solveUsingBitMasking(n,m,row+1,0,currmask,0,dp)%mod);\n }\n\n long long count = 0;\n for(int color=1;color<=3;color++){\n long long upperColor = (premask >> (2*col))&3;\n long long leftColor = -1;\n if(col>0){\n leftColor = (currmask>>(2*col-2))&3;\n }\n //00: Blank\n //01: G\n //10: B\n //11: R\n if(leftColor != color && upperColor != color){\n count += (solveUsingBitMasking(n,m,row,col+1,premask, currmask | (color<<(2*col)), dp)%mod);\n count = count % mod;\n }\n }\n \n if(col == 0) dp[row][premask] = count;\n return count;\n }\n\n\n int colorTheGrid(int m, int n) {\n //_______________________________________________\n //Biggest hint for bitmasking is size of \'m\'\n //_______________________________________________\n\n vector<unordered_map<long long,long long>> dp(n);\n return solveUsingBitMasking(n,m,0,0,0,0,dp);\n\n // vector<vector<int>> grid(n, vector<int>(m, -1));\n // vector<vector<int>> dp(n, vector<int>(m, -1));\n // return solveUsingRecursion(n,m,grid,0,0);\n }\n};\n```
0
0
['Dynamic Programming', 'Bitmask', 'C++']
0
painting-a-grid-with-three-different-colors
Python 3: TC O(8**m log(n)), SC O(4**m): Transition Matrix, Scaling and Squaring
python-3-tc-o8m-logn-sc-o4m-transition-m-dhjr
Intuition\n\nWe want the total ways. A natural subproblem is to get the total ways to get n columns ending with each valid color pattern.\n\nIf we can do that,
biggestchungus
NORMAL
2024-07-30T21:49:25.234968+00:00
2024-07-30T21:49:25.234986+00:00
1
false
# Intuition\n\nWe want the total ways. A natural subproblem is to get the total ways to get `n` columns ending with each valid color pattern.\n\nIf we can do that, then for each color pattern `c`, we can\n* find all the other color patterns `c\'` we can append this column to\n* add up all ways to get `n-1` columns with patterns `c\'`\n\nThis is a classic DP problem. For each `c` we\'d iterate over the `O(numPatterns)` other patterns `c\'`, and if they\'re compatible, add the ways to make 1 fewer column with that pattern `c\'`.\n\n## Speeding Up: Transition Matrix\n\nThe above algorithm takes `O(numPatterns**2)` for each number of columns, so `O(numPatterns**2 * n)`.\n\nBut we also see above that the ways\n* only depends on the prior column\n* and the operation is linear and the same for all steps\n\nIn other words we can find a matrix `T` where `ways_n = T*ways_{n-1}`. `T[c, c\'] == 1` if you can append pattern `c` to pattern `c\'`. That way matrix multiplication is the same as the above sum of `c\'` ways for each `c`.\n\nBy induction we find that `ways_n = T * T * ways{n-2} = ... = T**(n-1)*ways_1`. We know `ways_1`: it\'s all ones, there\'s one way to make a single column with each pattern.\n\nSo if we can\n* get all of the valid single column arrangements\n* and fill in `T[c, c\']`, 1 if `c` and `c\'` are compatible and 0 otherwise\n* and compute `T**(n-1)` in log time\n* then we get a much faster algorithm for large `n`\n\n# Approach\n\n## All Column Configs: DFS + BT\n\nWe can use DFS+backtracking to get all column configurations. The first color can be anything. Each subsequent color can be anything besides the prior color in that row.\n\n## Transition Matrix: Brute Force\n\nThen for each of the `C` column configurations\n* iterate over each `c in range(C)`\n* for `c\' != c` we can check if any color are the same, if so then we can\'t attach `c` to `c\'`. Otherwise we can, and we set `T[c, c\'] = 1`. The logic is the same if we swap `c` and `c\'` so `T` is symmetric\n\n## Fast `T**(n-1)`: Scaling and Squaring\n\nWe can use the classic scale-and-square method. It works just as well*** for matrices as it does for scalars:\n* for the current bit `b` of `n`, we need\n * `T**b`, which I call `P` for "current **P**ower of T"\n * the accumulation of products `T**(n-1)`\n\nMatrix multiplication is all products and summation, which commute with taking residues mod `BIG`. Therefore we can aggressively reduce values mod `BIG` to avoid overflow.\n\n*** "just as well" isn\'t quite true: BE VERY VERY CAREFUL ABOUT OVERFLOW. In fact, in this problem, I had overflow problems when trying to use numpy!\n\nThe reason is entries in a matrix can obviously be up to `BIG-1`. When we take a matrix product, numpy does not do any modular arithmetic, there\'s no option for it. For `m=5` there are 48 column patterns, so we\'re summing 48 products of max size `BIG-1` squared. Yikes. That works out to be `2 ** 65.5` or so with a calculator, which is above `np.uint64`, the largest integer datatype. Floats go higher, but we\'d get roundoff problems.\n\n**So we can\'t use numpy in this problem because of overflow** Instead, I wrote my own "mult_mod" function that does matrix multiplication A*B mod `BIG`.\n\n# Complexity\n- Time complexity:\n - DFS + BT: `O(m)` ops for each column config, of which there are `3*2**(m-1)` for a total of `O(m*2**(m-1))`\n - filling in `T`: `O(m)` for each pair, so `O(m*2**(2*m))` operations, `2**(m-1)` squared pairs\n - matrix multiplies: we have `2**(m-1)` rows and columns, so matrix multiplication is cubic in that for `O(8**m)` operations. This is the leading order of complexity\n - for scaling and squaring we need to do `O(log(n))` matrix multiplications, hence the overall complexity\n\n- Space complexity: `O(4**m)`, our matrices have `O(2**m)` rows and columns, and thus `O(2**m * 2**m) = O(4**m)` entries\n\n## Further Improvements?\n\nWe could probably reduce space usage if we got rid of the scaling-and-squaring, and instead stored `T` as a sparse matrix. Then we\'d have to do `O(N)` multiplies, but `T` would take a lot less space to store.\n\nI think the trick to these problems in general is to identify the shorter axis and exploit the rows >> cols or cols >> rows to speed things up.\n\nIn this case cols >> rows so we picked an approach that scales very favorably in `n`, not so much obviously in `m`.\n\n# Code\n```\nimport numpy as np\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n # m x n grid\n #\n # each cell is initially white\n # > paint each cell r, g, b\n # > all must be painted\n # Return the number of ways to color the grid with no two adj cells having the same color\n\n # neat. combinatorics, row/col optimization probably, etc.\n\n # wlog have to color the first row, which is special b/c there are no constraints on it\n # other than within the same row\n\n # 3 ways to pick the first cell\n # then 2 diff colors exist for the next\n # and 2 diff after that for the next, etc.\n # for a total of 3*2**(n-1) ways\n\n # c0 c1 c2 c3 c4 ...\n # c1 ? # if we start with c1, we have two choices b/c there\'s one unique color\n # # if we start with the third color, then ? has only one choice\n # this gets complicated, probably there\'s an optimization but hard to say\n\n ## so something a bit more brute force: notice that m <= 5 so rows are very short, cheap\n #\n # idea: we can form all of the 3*2**4 = 48 column configurations\n # and the columns they can attach to\n # then we can use a transition matrix approach\n\n BIG = 10**9+7\n\n if m == 1:\n return 3 * pow(2, n-1, BIG) % BIG # 3 choices for first, each later has 2 different colors\n\n # all configs: DFS + bt\n configs = []\n curr = []\n def dfs(r: int) -> None:\n if r == 0:\n for c in \'rgb\':\n curr.append(c)\n dfs(1)\n curr.pop()\n elif r == m:\n configs.append(\'\'.join(curr))\n else:\n for c in \'rgb\':\n if c == curr[-1]: continue\n\n curr.append(c)\n dfs(r+1)\n curr.pop()\n\n dfs(0)\n\n # build transition matrix\n C = len(configs)\n T = [[0]*C for _ in range(C)]\n for c1 in range(C):\n for c2 in range(c1):\n if all(a != b for a, b, in zip(configs[c1], configs[c2])):\n # no conflicts: we can append a column of config c1 to c2 and vice-versa\n T[c1][c2] = 1\n T[c2][c1] = 1\n\n # TODO: use Lapack, etc. to exploit the symmetric nature of the transition matrix\n \n # we advance to 2, 3, etc. ways, n-1 total. If we represent ways_n, the ways to end with\n # each column pattern after n steps as a vector of length C, then\n # > ways_n = T*ways_{n-1}\n # = T*T*ways{n-2}\n # = ...\n # = T**(n-1) * ways_1\n #\n # We know ways_1 is the ones vector; there is one way to have a single column in each of\n # the single columns\n #\n # So we can use scaling-and-squaring mod BIG to get T**(n-1) in log time\n \n def mult_mod(A, B):\n """Returns A.dot(B) mod BIG"""\n # we need this because A.dot(B) in numpy doesn\'t have a mod argument\n # as a result we have have up to 48 entries of size BIG-1 multiplied together\n # and 48*(BIG-1)**2 is above the max uint64 value!!\n\n out = [[0]*C for _ in range(C)]\n for i in range(C):\n for j in range(C):\n for k in range(C):\n out[i][j] = (out[i][j] + A[i][k]*B[k][j]) % BIG\n\n return out\n\n # repeated scaling and squaring\n n -= 1\n Tn = [[0]*C for _ in range(C)]\n for i in range(C): Tn[i][i] = 1\n P = [t[:] for t in T]\n while n:\n if n & 1:\n Tn = mult_mod(Tn, P)\n\n # move on to next bit of n\n # lsb will be 2*lsb, and thus P**(2*lsb) == (P**lsb) ** 2\n P = mult_mod(P, P)\n n >>= 1\n\n return sum(sum(row) for row in Tn) % BIG\n```
0
0
['Python3']
0
painting-a-grid-with-three-different-colors
👍Runtime 167 ms Beats 100.00%
runtime-167-ms-beats-10000-by-pvt2024-6pnc
Code\n\nconst mod = 1e9 + 7\n\nfunc colorTheGrid(m int, n int) int {\n\tstate := make(map[int]int64)\n\tdfs(state, 0, m, -1, 0)\n\tset := make([]int, 0, len(sta
pvt2024
NORMAL
2024-07-08T03:15:38.413888+00:00
2024-07-08T03:15:38.413926+00:00
5
false
# Code\n```\nconst mod = 1e9 + 7\n\nfunc colorTheGrid(m int, n int) int {\n\tstate := make(map[int]int64)\n\tdfs(state, 0, m, -1, 0)\n\tset := make([]int, 0, len(state))\n\tfor k := range state {\n\t\tset = append(set, k)\n\t}\n\n\tfor i := 1; i < n; i++ {\n\t\tdp := make(map[int]int64)\n\t\tfor _, a := range set {\n\t\t\tfor _, b := range set {\n\t\t\t\tif a&b == 0 {\n\t\t\t\t\tdp[a] = (dp[a] + state[b]) % mod\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstate = dp\n\t}\n\n\tres := int64(0)\n\tfor _, val := range state {\n\t\tres = (res + val) % mod\n\t}\n\treturn int(res)\n}\n\nfunc dfs(state map[int]int64, j, m, prev, cur int) {\n\tif j == m {\n\t\tstate[cur]++\n\t\treturn\n\t}\n\tfor i := 0; i < 3; i++ {\n\t\tif i == prev {\n\t\t\tcontinue\n\t\t}\n\t\tdfs(state, j+1, m, i, (cur<<3)|(1<<i))\n\t}\n}\n```
0
0
['Go']
0
painting-a-grid-with-three-different-colors
DP
dp-by-yoongyeom-fl1f
Code\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n t = [\'a\', \'b\', \'c\']\n for i in range(m-1):\n new =
YoonGyeom
NORMAL
2024-05-19T13:16:45.661991+00:00
2024-05-19T13:16:45.662023+00:00
12
false
# Code\n```\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n t = [\'a\', \'b\', \'c\']\n for i in range(m-1):\n new = []\n for s in t:\n if s[-1] != \'a\': new.append(s+\'a\')\n if s[-1] != \'b\': new.append(s+\'b\')\n if s[-1] != \'c\': new.append(s+\'c\')\n t = new\n d = defaultdict(set)\n for s1, s2 in itertools.combinations(t, 2):\n for i in range(m):\n if s1[i] == s2[i]: break\n if i == m-1: \n d[s1].add(s2)\n d[s2].add(s1)\n @cache\n def dp(s, n):\n if n == 0: return 1\n res = 0\n for ch in d[s]:\n res += dp(ch, n-1)\n return res\n return sum(dp(s, n-1) for s in t)%(10**9+7)\n```
0
0
['Python3']
0
painting-a-grid-with-three-different-colors
Simple DP solution✅✅
simple-dp-solution-by-jayesh_06-fgv1
\n\n# Code\n\nclass Solution {\npublic:\n int dp[1001][50];\n int mod=1e9+7;\n void genrate(int i,string& s,vector<string>& v,char ch,int m){\n
Jayesh_06
NORMAL
2024-05-09T07:44:51.969706+00:00
2024-05-09T07:44:51.969742+00:00
102
false
\n\n# Code\n```\nclass Solution {\npublic:\n int dp[1001][50];\n int mod=1e9+7;\n void genrate(int i,string& s,vector<string>& v,char ch,int m){\n if(i==m){\n v.push_back(s);\n return ;\n }\n if(ch!=\'R\'){\n s+=\'R\';\n genrate(i+1,s,v,\'R\',m);\n s.pop_back();\n }\n if(ch!=\'G\'){\n s+=\'G\';\n genrate(i+1,s,v,\'G\',m);\n s.pop_back();\n }\n if(ch!=\'B\'){\n s+=\'B\';\n genrate(i+1,s,v,\'B\',m);\n s.pop_back();\n }\n }\n int find(int i,vector<string>& v,int pre,int m,int n){\n if(i==n){\n return 1;\n }\n if(dp[i][pre+1]!=-1){\n return dp[i][pre+1];\n }\n long long ways=0;\n string last;\n if(pre!=-1){\n last=v[pre];\n }\n for(int j=0;j<v.size();j++){\n bool same=false;\n if(pre!=-1){\n for(int k=0;k<m;k++){\n if(last[k]==v[j][k]){\n same=true;\n break;\n }\n }\n }\n if(!same){\n ways=(ways+find(i+1,v,j,m,n))%mod;\n }\n \n \n }\n return dp[i][pre+1]=ways;\n }\n int colorTheGrid(int m, int n) {\n memset(dp,-1,sizeof(dp));\n vector<string> v;\n string s="";\n genrate(0,s,v,\'M\',m);\n return find(0,v,-1,m,n)%mod;\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0
painting-a-grid-with-three-different-colors
Space Optimized DP
space-optimized-dp-by-abhishequmar-kx9u
Code\n\n#include <bits/stdc++.h>\n\n#define pb push_back\n#define po pop_back\n#include <string>\nusing namespace std;\n\ntemplate <typename T>\nstd::istream &o
abhishequmar
NORMAL
2024-03-24T02:03:17.736917+00:00
2024-03-24T02:03:17.736951+00:00
21
false
# Code\n```\n#include <bits/stdc++.h>\n\n#define pb push_back\n#define po pop_back\n#include <string>\nusing namespace std;\n\ntemplate <typename T>\nstd::istream &operator>>(std::istream &in, std::vector<T> &v){for(int i =0;i<v.size();i++){in>>v[i];}return in;}\n\ntemplate <typename A, typename B>\nostream &operator<<(ostream &os, const pair<A, B> &p) { return os << \'(\' << p.first << ", " << p.second << \')\'; }\ntemplate <typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type>\nostream &operator<<(ostream &os, const T_container &v)\n{\n os << \'{\';\n string sep;\n for (const T &x : v)\n os << sep << x, sep = ", ";\n return os << "}";\n}\nvoid dbg_out() { cerr << endl; }\ntemplate <typename Head, typename... Tail>\nvoid dbg_out(Head H, Tail... T)\n{\n cerr << \' \' << H;\n dbg_out(T...);\n}\n#ifdef LOCAL\n#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)\n#else\n#define dbg(...)\n#endif\n\n// #define ar array\n#define ll long long\n// #define ld long double\n// #define sza(x) ((int)x.size())\n#define all(a) (a).begin(), (a).end()\n\nclass Solution {\npublic:\n bool iscompatible(vector<int>& a, vector<int>& b){\n for(int i=0;i<a.size();i++){\n if(a[i]==b[i]){\n return false;\n }\n }\n return true;\n }\n vector<vector<int>> gen(int n){\n set<vector<int>>prev;\n vector<int>b(n, -1);\n prev.insert(b);\n for(int i=0;i<n;i++){\n set<vector<int>>cur;\n for(auto j:prev){\n vector<int>t=j;\n for(int k=0;k<3;k++){\n if(i==0){\n t[i]=k;\n }else if(t[i-1]!=k){\n t[i]=k;\n }\n if(t[i]!=-1){\n cur.insert(t);\n }\n }\n }\n prev=cur;\n }\n vector<vector<int>>ans;\n for(auto i:prev){\n ans.push_back(i);\n }\n return ans;\n }\n int colorTheGrid(int m, int n) {\n long long mod=1e9 + 7;\n vector<vector<int>>prev=gen(m);\n map<vector<int>, long long>mprev;\n\n for(auto i:prev){\n mprev[i]++;\n }\n\n for(int i=1;i<n;i++){\n vector<vector<int>>cur=prev;\n map<vector<int>, long long>mcur;\n for(int j=0;j<prev.size();j++){\n for(int k=0;k<prev.size();k++){\n if(iscompatible(cur[j], prev[k])){\n mcur[cur[j]]=(mcur[cur[j]]+mprev[prev[k]])%mod;\n }\n }\n }\n mprev=mcur;\n }\n\n\n int res=0;\n for(auto i:mprev){\n res=(res+i.second)%mod;\n }\n\n return res;\n\n\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0