LeetCode解题报告
  • LeetCode解题报告
  • Easy
    • 1086. High Five
    • 283. Move Zeros
    • 443. String Compression
    • 38. Count and Say
    • 169. Majority Element
    • 349. Intersection of Two Arrays
    • 58. Length of Last Word
    • 70. Climbing Stairs
    • 455. Assign Cookies
    • 83. Remove Duplicates from Sorted List
    • 160. Intersection of Two Linked Lists
    • 206. Reverse Linked List
    • 122. Best Time to Buy and Sell Stock II
    • 760. Find Anagram Mappings
    • 804. Unique Morse Code Words
    • 905. Sort Array By Parity
    • 852. Peak Index in a Mountain Array
    • 961. N-Repeated Element in Size 2N Array
    • 832. Flipping an Image
    • 617. Merge Two Binary Trees
    • 700. Search in a Binary Search Tree
    • 409. Longest Palindrome
    • 657. Robot Return to Origin
    • 942. DI String Match
    • 728. Self Dividing Numbers
    • 944. Delete Columns to Make Sorted
    • 509. Fibonacci Number
    • 1021. Remove Outermost Parentheses
    • 171. Excel Sheet Column Number
    • 999. Available Captures for Rook
    • 252. Meeting Rooms
    • 482. License Key Formatting
    • 844. Backspace String Compare
    • 938. Range Sum of BST
    • 557. Reverse Words in a String III
    • 922. Sort Array By Parity II
    • 559. Maximum Depth of N-ary Tree
    • 849. Maximize Distance to Closest Person
    • 463. Island Perimeter
    • 665. Non-decreasing Array
    • 53. Maximum Subarray
    • 448. Find All Numbers Disappeared in an Array
    • 141. Linked List Cycle
    • 937. Reorder Log Files
    • 303. Range Sum Query - Immutable
    • 1103. Distribute Candies to People
    • 202. Happy Number
    • 232. Implement Queue using Stacks
    • 1119. Remove Vowels from a String
    • 9. Palindrome Number
    • 266. Palindrome Permutation
    • 125. Valid Palindrome
    • 246. Strobogrammatic Number
    • 168. Excel Sheet Column Title
    • 38. Count and Say
    • 242. Valid Anagram
    • 290. Word Pattern
    • 293. Flip Game
    • 205. Isomorphic Strings
    • 345. Reverse Vowels of a String
    • 344. Reverse String
    • 383. Ransom Note
    • 387. First Unique Character in a String
    • 58. Length of Last Word
    • 14. Longest Common Prefix
    • 1122. Relative Sort Array
    • 219. Contains Duplicate II
    • 13. Roman to Integer
    • 169. Majority Element
    • 299. Bulls and Cows
    • 290. Word Pattern
    • 205. Isomorphic Strings
    • 744. Find Smallest Letter Greater Than Target
    • 763. Partition Labels
    • 110. Balanced Binary Tree
    • 543. Diameter of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 392. Is Subsequence
    • 20. Valid Parentheses
    • 7. Reverse Integer
    • 66. Plus One
    • 258. Add Digits
    • 67. Add Binary
    • 367. Valid Perfect Square
    • 204. Count Primes
    • 941. Valid Mountain Array
    • 100. Same Tree
    • 101. Symmetric Tree
    • 226. Invert Binary Tree
    • 257. Binary Tree Paths
    • 112. Path Sum
    • 113. Path Sum II
    • 104. Maximum Depth of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 110. Balanced Binary Tree
    • 107. Binary Tree Level Order Traversal II
    • 235. Lowest Common Ancestor of a Binary Search Tree
    • 256. Paint House
    • 1165. Single-Row Keyboard
    • 637. Average of Levels in Binary Tree
    • 141. Linked List Cycle
    • 276. Paint Fence
    • 237. Delete Node in a Linked List
    • 203. Remove Linked List Elements
    • 21. Merge Two Sorted Lists
    • 278. First Bad Version
    • 35. Search Insert Position
    • 349. Intersection of Two Arrays
    • 350. Intersection of Two Arrays II
    • 234. Palindrome Linked List
    • 937. Reorder Data in Log Files
    • 733. Flood Fill
    • 1114. Print in Order
    • 27. Remove Element
    • 339. Nested List Weight Sum
    • 155. Min Stack
    • 225. Implement Stack using Queues
    • 389. Find the Difference
    • 136. Single Number
    • 26. Remove Duplicates from Sorted Array
    • 80. Remove Duplicates from Sorted Array II
    • 189. Rotate Array
    • 572. Subtree of Another Tree
    • 359. Logger Rate Limiter
    • 346. Moving Average from Data Stream
    • 118. Pascal's Triangle
    • 119. Pascal's Triangle II
    • 217. Contains Duplicate
    • 243. Shortest Word Distance
    • 121. Best Time to Buy and Sell Stock
  • Medium
    • 621. Task Scheduler
    • 1823. Find the Winner of the Circular Game
    • 340. Longest Substring with At Most K Distinct Characters
    • 209. Minimum Size Subarray Sum
    • 142. Linked List Cycle II
    • 451. Sort Characters By Frequency
    • 503. Next Greater Element II
    • 807. Max Increase to Keep City Skyline
    • 285. Inorder Successor in BST
    • 395. Longest Substring with At Least K Repeating Characters
    • 12. Integer to Roman
    • 807. Max Increase to Keep City Skyline
    • 392. Is Subsequence
    • 763. Partition Labels
    • 1110. Delete Nodes And Return Forest
    • 1109. Corporate Flight Bookings
    • 370. Range Addition
    • 238. Product of Array Except Self
    • 3. Longest Substring Without Repeating Characters
    • 161. One Edit Distance
    • 249. Group Shifted Strings
    • 49. Group Anagrams
    • 6. ZigZag Conversion
    • 294. Flip Game II
    • 345. Reverse Vowels of a String
    • 151. Reverse Words in a String
    • 324. Wiggle Sort II
    • 215. Kth Largest Element in an Array
    • 280. Wiggle Sort
    • 56. Merge Intervals
    • 287. Find the Duplicate Number
    • 11. Container With Most Water
    • 271. Encode and Decode Strings
    • 5. Longest Palindromic Substring
    • 39. Combination Sum
    • 229. Majority Element II
    • 275. H-Index II
    • 244. Shortest Word Distance II
    • 55. Jump Game
    • 245. Shortest Word Distance III
    • 40. Combination Sum II
    • 216. Combination Sum III
    • 77. Combinations
    • 78. Subsets
    • 90. Subsets II
    • 131. Palindrome Partitioning
    • 17. Letter Combinations of a Phone Number
    • 739. Daily Temperatures
    • 46. Permutations
    • 49. Group Anagrams
    • 253. Meeting Rooms II
    • 540. Single Element in a Sorted Array
    • 267. Palindrome Permutation II
    • 187. Repeated DNA Sequences
    • 165. Compare Version Numbers
    • 43. Multiply Strings
    • 144. Binary Tree Preorder Traversal
    • 94. Binary Tree Inorder Traversal
    • 102. Binary Tree Level Order Traversal
    • 129. Sum Root to Leaf Numbers
    • 298. Binary Tree Longest Consecutive Sequence
    • 337. House Robber III
    • 103. Binary Tree Zigzag Level Order Traversal
    • 199. Binary Tree Right Side View
    • 1169. Invalid Transactions
    • 98. Validate Binary Search Tree
    • 236. Lowest Common Ancestor of a Binary Tree
    • 254. Factor Combinations
    • 47. Permutations II
    • 31. Next Permutation
    • 60. Permutation Sequence
    • 62. Unique Paths
    • 63. Unique Paths II
    • 279. Perfect Squares
    • 139. Word Break
    • 322. Coin Change
    • 64. Minimum Path Sum
    • 221. Maximal Square
    • 24. Swap Nodes in Pairs
    • 328. Odd Even Linked List
    • 92. Reverse Linked List II
    • 120. Triangle
    • 82. Remove Duplicates from Sorted List II
    • 2. Add Two Numbers
    • 33. Search in Rotated Sorted Array
    • 81. Search in Rotated Sorted Array II
    • 153. Find Minimum in Rotated Sorted Array
    • 162. Find Peak Element
    • 374. Guess Number Higher or Lower
    • 34. Find First and Last Position of Element in Sorted Array
    • 300. Longest Increasing Subsequence
    • 48. Rotate Image
    • 54. Spiral Matrix
    • 59. Spiral Matrix II
    • 73. Set Matrix Zeroes
    • 311. Sparse Matrix Multiplication
    • 74. Search a 2D Matrix
    • 240. Search a 2D Matrix II
    • 370. Range Addition
    • 79. Word Search
    • 200. Number of Islands
    • 994. Rotting Oranges
    • 286. Walls and Gates
    • 323. Number of Connected Components in an Undirected Graph
    • 130. Surrounded Regions
    • 60. Permutation Sequence
    • 127. Word Ladder
    • 79. Word Search
    • 364. Nested List Weight Sum II
    • 150. Evaluate Reverse Polish Notation
    • 394. Decode String
    • 347. Top K Frequent Elements
    • 332. Reconstruct Itinerary
    • 341. Flatten Nested List Iterator
    • 318. Maximum Product of Word Lengths
    • 207. Course Schedule
    • 210. Course Schedule II
    • 384. Shuffle an Array
    • 277. Find the Celebrity
    • 133. Clone Graph
    • 399. Evaluate Division
    • 356. Line Reflection
    • 310. Minimum Height Trees
    • 223. Rectangle Area
    • 261. Graph Valid Tree
    • 211. Add and Search Word - Data structure design
    • 208. Implement Trie (Prefix Tree)
    • 362. Design Hit Counter
    • 281. Zigzag Iterator
    • 8. String to Integer (atoi)
    • 15. 3Sum
    • 18. 4Sum
    • 134. Gas Station
    • 981. Time Based Key-Value Store
    • 1007. Minimum Domino Rotations For Equal Row
    • 1057. Campus Bikes
    • 309. Best Time to Buy and Sell Stock with Cooldown
  • Hard
    • 4. Median of Two Sorted Arrays
    • 188. Best Time to Buy and Sell Stock IV
    • 123. Best Time to Buy and Sell Stock III
    • 145. Binary Tree Postorder Traversal
    • 265. Paint House II
    • 154. Find Minimum in Rotated Sorted Array II
    • 315. Count of Smaller Numbers After Self
    • 305. Number of Islands II
    • 42. Trapping Rain Water
    • 45. Jump Game II
Powered by GitBook
On this page

Was this helpful?

  1. Medium

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.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

解题要点:

首先把边界的‘O'以及与其相邻的’O'全变为不有效字符(在此我用‘#’),来处理不被包围的’O'。然后把其他‘O'全部转换为’X'(被包围的‘O'),最后把‘#’改回‘O'。

class Solution(object):
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: None Do not return anything, modify board in-place instead.
        """
        if board == None or len(board) == 0:
            return
        n = len(board)
        m = len(board[0])
        def search(board, i, j):
            queue = [(i, j)]
            while queue:
                r, c = queue.pop(0)
                if r - 1 >= 0 and board[r-1][c] == 'O':
                    board[r-1][c] = '#'
                    queue.append((r-1,c))
                if r + 1 < n and board[r+1][c] == 'O':
                    board[r+1][c] = '#'
                    queue.append((r+1,c))
                if c - 1 >= 0 and board[r][c-1] == 'O':
                    board[r][c-1] = '#'
                    queue.append((r,c-1))
                if c + 1 < m and board[r][c+1] == 'O':
                    board[r][c+1] = '#'
                    queue.append((r,c+1))
        for i in range(n):
            for j in range(m):
                if i == 0 and board[i][j] == 'O':
                    board[i][j] = '#'
                    search(board, i, j)
                if i == n-1 and board[i][j] == 'O':
                    board[i][j] = '#'
                    search(board, i, j)
                if i > 0 and i < n-1 and j == 0 and board[i][j] == 'O':
                    board[i][j] = '#'
                    search(board, i, j)
                if i > 0 and i < n-1 and j == m-1 and board[i][j] == 'O':
                    board[i][j] = '#'
                    search(board, i, j)
        for i in range(n):
            for j in range(m):
                if board[i][j] == 'O':
                    board[i][j] = 'X'
        for i in range(n):
            for j in range(m):
                if board[i][j] == '#':
                    board[i][j] = 'O'
        
Previous323. Number of Connected Components in an Undirected GraphNext60. Permutation Sequence

Last updated 5 years ago

Was this helpful?