Determine Color of a Chessboard Square


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 Determine Color of a Chessboard Square algorithms c / c++ math

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.

1
2
3
4
5
6
7
8
9
10
11
12
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);
        }
    }
};
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) —

GD Star Rating
loading...
352 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

Leave a Reply