saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • DFS
  • BFS
  • 알고리즘
  • 알고리즘문제해결
  • LeetCode
  • 취업준비
  • c++
  • 파이썬
  • Python
  • 릿코드
  • 리트코드
  • 백준
  • 개발자 취업준비
  • 취준
  • 딥러닝
  • 문제해결능력
  • 온라인저지
  • 개발자
  • two pointer
  • 딕셔너리

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

[LeetCode] 130. Surrounded Regions
컴퓨터공학/LeetCode 1000

[LeetCode] 130. Surrounded Regions

2022. 11. 9. 09:06

130. Surrounded Regions

Medium

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

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

 

Example 1:

Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.

Example 2:

Input: board = [["X"]]
Output: [["X"]]

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.

문제 풀이

  • 2차원 배열이 주어진다. 
  • 2차원 배열에는 X, O가 들어있다. 
  • X로 둘러쌓인 O를 X로 뒤집어야한다.
  • 하지만 O가 경계에 닿아있다면 그 O에 이어져있는 O들은 뒤집지 않아도 된다. 
  • 즉 경계에 있는 O가 붙어있지 않으면 모두 O를 X로 뒤집어주면되는 것이다. 
  • 완전 탐색을 해야하는데, 제한 사항을 보면 2차원 배열의 최대 길이가 각각 200이다. 
  • 하지만 문제를 이해해보면 O들만 확인해보면되서 BFS로도 풀 수 있다. 
  • O의 좌표를 모두 저장하고, BFS를 각각 돌리면서 현재 O위치의 좌표를 모두 임시 저장한다.
  • flag를 정해서 이어진 O가 경계에 닿아있다면 1로 바꿔준다.
  • 경계에 닿아있는 O가 한개도 없다면 2차원 배열에는 O 혹은 X 밖에 없기 때문에, O를 X로 뒤집어줘야한다.

소스 코드

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        dr = [[0, 1], [1, 0], [-1, 0], [0, -1]]
        que = []
        o_lst = []
        visited = set()
        n, m = len(board), len(board[0])
        for i in range(n):
            for j in range(m):
                if board[i][j] == 'O':
                    o_lst.append((i, j))
        
        for node in o_lst:
            if node in visited: continue
            visited.add(node)
            que.append(node)
            flag = 0
            temp = []
            temp.append(node)
            while que:
                cur_node = que.pop(0)
                cur_y = cur_node[0]
                cur_x = cur_node[1]
                for op_y, op_x in dr:
                    nxt_y = cur_y + op_y
                    nxt_x = cur_x + op_x
                    if nxt_y < 0 or nxt_x < 0 or nxt_y >= n or nxt_x >= m:
                        flag = 1
                        continue
                    if (nxt_y, nxt_x) in visited: continue
                    if board[nxt_y][nxt_x] == 'O':
                        temp.append((nxt_y, nxt_x))
                        visited.add((nxt_y, nxt_x))
                        que.append((nxt_y, nxt_x))
            if flag == 0:
                for ty, tx in temp:
                    board[ty][tx] = 'X'
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 139. Word Break  (1) 2022.11.11
[LeetCode] 131. Palindrome Partitioning  (0) 2022.11.10
[LeetCode] 124. Binary Tree Maximum Path Sum  (0) 2022.11.09
[LeetCode] 84. Largest Rectangle in Histogram  (0) 2022.11.09
[LeetCode] 25. Reverse Nodes in k-Group  (1) 2022.11.03
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 139. Word Break
    • [LeetCode] 131. Palindrome Partitioning
    • [LeetCode] 124. Binary Tree Maximum Path Sum
    • [LeetCode] 84. Largest Rectangle in Histogram
    saurus2
    saurus2
    Simple is Best

    티스토리툴바