Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 51. N-Queens
  • 130. Surrounded Regions

Was this helpful?

  1. 9. DFS

General

51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Example:

[
  // Solution 1
  [".Q..",
   "...Q",
   "Q...",
   "..Q."
  ],
  // Solution 2
  ["..Q.",
   "Q...",
   "...Q",
   ".Q.."
  ]
]
  • 比較newRow不能在已有的垂直線上, row和newRow的距離上

def solveNQueens(self, n: int) -> List[List[str]]:
    ans = []
    self.dfs(0, n, [], ans)
    return ans

def dfs(self, row, n, cands, ans):
    if row == n:
        ans.append(self.build(cands))
        
    for idx in range(n):
        if self.isValid(cands,idx):
            # print(row)
            self.dfs(row+1, n, cands + [idx], ans)
        
def isValid(self, cands, idx):
    n = len(cands)
    for i in range(n):
        diff = abs(cands[i] - idx)
        if diff == 0 or diff == (n - i): # 跟第i層的距離
            return False
    return True

def build(self, cands):
    grid = []
    for idx in cands:
        line = ''
        for j in range(len(cands)):
            line += 'Q' if j == idx else '.'   
        grid.append(line)
    return grid

130. Surrounded Regions

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

  • 掃描邊界,遇到'O', dfs翻成'*'

  • 遍歷每一層,遇到'*'翻回'O', 遇到'O'翻成'X'

def solve(self, board: List[List[str]]) -> None:
    if not board: return
    
    self.m, self.n = len(board), len(board[0])
    # trasere the border and mark all 'o' to '#'
    for i in [0, self.m-1]:
        for j in range(self.n):
            if board[i][j] == 'O':
                self.dfs(i, j, board)      
    for i in range(1, self.m-1):
        for j in [0, self.n-1]:
            if board[i][j] == 'O':
                self.dfs(i, j, board)
                
    # mark 'O' to 'X', '#' to O
    for i in range(self.m):
        for j in range(self.n):
            if board[i][j] == '*':
                board[i][j] = 'O'
            elif board[i][j] == 'O':
                board[i][j] = 'X'
            

def dfs(self, i, j, board):
    board[i][j] = '*'
    
    for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        y = i + dy
        x = j + dx
        
        if not (0 <= y < self.m and 0 <= x < self.n): continue
        if board[y][x] == 'O':
            self.dfs(y, x, board)
PreviousBacktrackNextSubset

Last updated 5 years ago

Was this helpful?