Matrix Flashcards

(3 cards)

1
Q

Given m x n matrix, what’s the formula to compute the number the diagonals in the matrix even if m != n?

A

diagonal_cnt = m + n - 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Given 2 positions in a matrix, implement a tiny method to check if they are on the same diagonal.

input: row1, col1, row2, col2
output: True or False

A
def is_same_diagonal(row1, col1, row2, col2):
          # same left diagonal?                     # same right diagonal?
return ((row1 - col1) == (row2 - col2)) or ((row1 + col1) == (row2 + col2))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Implement

Solution to the N-Queens Problem with time complexity of O(N!) and space complexity of O(N)

A
def solve_n_queens_count(n):
    count = 0

    def backtrack(row, cols, slash_diags, backslash_diags):
        nonlocal count
        if row == n:
            count += 1
            return

        for col in range(n):
            slash = row - col
            backslash = row + col

            if col in cols or slash in slash_diags or backslash in backslash_diags:
                continue

            # Choose
            cols.add(col)
            slash_diags.add(slash)
            backslash_diags.add(backslash)

            # Explore
            backtrack(row + 1, cols, slash_diags, backslash_diags)

            # Unchoose
            cols.remove(col)
            slash_diags.remove(slash)
            backslash_diags.remove(backslash)

    backtrack(0, set(), set(), set())
    return count
How well did you know this?
1
Not at all
2
3
4
5
Perfectly