Algorithms, Blockchain and Cloud

Determine Color of a Chessboard Square

chessboard

Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

chessboard

Example 1:
Input: coordinates = “a1”
Output: false
Explanation: From the chessboard above, the square with coordinates “a1” is black, so return false.

Example 2:
Input: coordinates = “h3”
Output: true
Explanation: From the chessboard above, the square with coordinates “h3” is white, so return true.

Example 3:
Input: coordinates = “c7”
Output: false

Constraints:
coordinates.length == 2
‘a’ <= coordinates[0] <= ‘h’
‘1’ <= coordinates[1] <= ‘8’

Hints:
Convert the coordinates to (x, y) – that is, “a1” is (1, 1), “d7” is (4, 7).
Try add the numbers together and look for a pattern.

Chessboard Square Color Algorithm

As you may observe, the colours of every adjacent rows are opposite. And every adjacent columns are opposite. Thus, we need to get the row and column from the given coordinate string and then we can check respectively.

class Solution {
public:
    bool squareIsWhite(string coordinates) {
        int col = coordinates[0] - 'a';
        int rows = coordinates[1] - '0';
        if (rows & 1) {
            return col & 1;
        } else {
            return 1 - (col & 1);
        }
    }
};

The time complexity and space complexity is O(1) constant.

See also: The Chess AI – Model Base or Machine Learning

–EOF (The Ultimate Computing & Technology Blog) —

335 words
Last Post: Teaching Kids Programming - Depth First Search Algorithms to Determine a Univalue Binary Tree
Next Post: Teaching Kids Programming - Packing Boxes Algorithm using GroupBy

The Permanent URL is: Determine Color of a Chessboard Square (AMP Version)

Exit mobile version