Remove Colored Pieces If Both Neighbors Are The Same Color

Solution For Remove Colored Pieces If Both Neighbors Are The Same Color

The problem “Remove Colored Pieces If Both Neighbors Are The Same Color” on LeetCode can be solved using a simple observation that whenever we remove a piece with the same color of its neighbors, the overall pattern remains the same, and we can continue removing such pieces until we cannot remove any more.

Here is the detailed solution with an explanation:

  1. Traverse the string and identify pieces that have the same color as their neighbors.

  2. Remove those pieces and update the string.

  3. Repeat step 1 and 2 until we cannot remove any more pieces.

  4. Check the remaining pieces and determine the winner.

Let’s take an example to understand this better:

Example:
Input:
s = “AAABBC”
Output:
true

Explanation:
1. We can remove “AAA” and update the string to “BBC”.
2. We can not remove any more pieces as no pieces have the same color as their neighbors.
3. The remaining string is “BBC”, and as there is only one color left, the winner is player A.

Solution:

We will use two pointers to traverse the string, i and j, and a flag to determine the current player.

  1. Initialize i and j to 0.

  2. While i < j, keep moving j until we find a piece that has a different color than s[i] or j reaches the end of the string.

  3. If j has reached the end of the string, check if (j-i) >= 2, if yes, then we can remove the pieces, update the string, and return true as player A wins.

  4. Otherwise, move i = j and reset j to i+1.

  5. Repeat steps 2 to 4 until we cannot remove any more pieces.

  6. If there is only one color left, return true as player A wins, otherwise return false as player B wins.

Here is the python code implementation of the above solution:

class Solution:
def winnerOfGame(self, colors: str) -> bool:
n = len(colors)
i, j = 0, 1
flag_A = True
count_A, count_B = 0, 0

    while j < n:
        while j < n and colors[j] == colors[i]:
            j += 1

        if j-i >= 3 and flag_A:
            count_A += j-i-2
        elif j-i >= 3 and not flag_A:
            count_B += j-i-2

        i = j
        j = i+1

        flag_A = not flag_A

    if count_A > count_B:
        return True
    else:
        return False

The time complexity of the above solution is O(n), where n is the length of the input string.

Step by Step Implementation For Remove Colored Pieces If Both Neighbors Are The Same Color

Assuming we have a 2D array of colors represented by integers (0 = black, 1 = white):

for (int i = 0; i < colors.length; i++) {
     for (int j = 0; j < colors[i].length; j++) {
          if (i > 0 && j > 0 && colors[i][j] == colors[i-1][j] && colors[i][j] == colors[i][j-1]) {
               colors[i][j] = -1; // mark as removed
          }
     }
}
def remove_colored_pieces_if_both_neighbors_are_the_same_color(board):
    n = len(board)
    m = len(board[0])
    
    # Create a copy of the board
    copy = [[0] * m for _ in range(n)]
    
    # Perform a BFS from each node
    for i in range(n):
        for j in range(m):
            if copy[i][j] == 0 and board[i][j] != 'X':
                # Perform a BFS from node (i, j)
                bfs(board, copy, i, j)
    
    # The copy now contains the minimum number of colors needed to color the board
    return copy
    
    
def bfs(board, copy, i, j):
    # Perform a BFS from node (i, j)
    
    # Get the color of the starting node
    color = board[i][j]
    
    # Create a queue and add the starting node to it
    queue = [(i, j)]
    
    # Mark the starting node as visited
    copy[i][j] = 1
    
    # Loop through the queue
    while queue:
        # Get the next node in the queue
        node = queue.pop(0)
        
        # Get the row and column of the node
        row = node[0]
        col = node[1]
        
        # Check the node's neighbors
        for neighbor in get_neighbors(board, row, col):
            # Get the row and column of the neighbor
            nrow = neighbor[0]
            ncol = neighbor[1]
            
            # Check if the neighbor is the same color
            if board[nrow][ncol] == color:
                # Check if the neighbor has been visited
                if copy[nrow][ncol] == 0:
                    # Mark the neighbor as visited
                    copy[nrow][ncol] = 1
                    
                    # Add the neighbor to the queue
                    queue.append((nrow, ncol))
            else:
                # The neighbor is a different color, so we don't need to visit it
                copy[nrow][ncol] = 1
                

def get_neighbors(board, row, col):
    # Get the node's neighbors
    
    # Initialize an empty list of neighbors
    neighbors = []
    
    # Get the dimensions of the board
    n = len(board)
    m = len(board[0])
    
    # Check the top neighbor
    if row > 0:
        neighbors.append((row - 1, col))
        
    # Check the bottom neighbor
    if row < n - 1:
        neighbors.append((row + 1, col))
        
    # Check the left neighbor
    if col > 0:
        neighbors.append((row, col - 1))
        
    # Check the right neighbor
    if col < m - 1:
        neighbors.append((row, col + 1))
        
    return neighbors
var removeColor = function(board, color) {
    var rows = board.length,
        cols = board[0].length;
    
    var dfs = function(r, c) {
        if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== color) {
            return;
        }
        
        board[r][c] = null;
        dfs(r - 1, c);
        dfs(r + 1, c);
        dfs(r, c - 1);
        dfs(r, c + 1);
    };
    
    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < cols; j++) {
            if (board[i][j] === color) {
                dfs(i, j);
            }
        }
    }
    
    return board;
};
There are many ways to solve this problem. One approach would be to use a two-dimensional array to keep track of the colors of the pieces. Then, we could iterate through the array and check the neighbors of each piece to see if they are the same color. If they are, we would remove the piece from the array.
You can use a 2D array to store the board state. For each cell, check the left and right neighbors. If they are the same color, remove the cell. Repeat until no more cells can be removed.

var board = new int[][] { new int[] {1, 1, 1, 1}, new int[] {1, 2, 2, 1}, new int[] {1, 2, 2, 1}, new int[] {1, 1, 1, 1} }; // Iterate over the board until no more changes can be made. bool changed; do { changed = false; for (int i = 0; i < board.Length; i++) { for (int j = 0; j < board[i].Length; j++) { // Check if the current cell can be removed. if (j > 0 && j < board[i].Length - 1 && board[i][j] != 0 && board[i][j] == board[i][j - 1] && board[i][j] == board[i][j + 1]) { // Remove the cell. board[i][j] = 0; changed = true; } } } } while (changed);


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]