3 min read
607 words
Problem Statement
leetcode problem link
Solution [Accepted]
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
n = 8
WHITE = 0
BLACK = 1
matrix = [[0] * n for _ in range(n)]
isWhite = True
for row in range(n):
for col in range(n):
if isWhite:
matrix[row][col] = WHITE
else:
matrix[row][col] = BLACK
isWhite = not isWhite
isWhite = not isWhite
row = ord(coordinates[0]) - ord('a')
col = n - int(coordinates[1])
return matrix[row][col] == WHITE
public class Solution {
public bool SquareIsWhite(string coordinates) {
int n = 8;
int[][] matrix = new int[8][];
for (int i = 0; i < 8; i++)
{
matrix[i] = new int[8];
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (i % 2 == 0) {
if (j % 2 != 0) {
matrix[i][j] = 1;
}
} else {
if (j % 2 == 0) {
matrix[i][j] = 1;
}
}
}
}
int row = coordinates[0] - 'a';
int col = n - (coordinates[1] - '0');
return matrix[row][col] == 0;
}
}
- time: O(n^2)
- space: O(n^2)
Optimize Solution
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
# Convert column letter to 0-based index (a=0, b=1, ..., h=7)
col = ord(coordinates[0]) - ord('a')
# Convert row number to 0-based index (1=0, 2=1, ..., 8=7)
row = int(coordinates[1]) - 1
# Chessboard pattern: square is white when sum of indices is odd
return (col + row) % 2 == 1
Leave a comment