엔지니어 게시판
LeetCode 솔루션 분류

[11/24] 79. Word Search

컨텐츠 정보

본문

Medium
12096487Add to ListShare

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

 

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

 

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

 

Follow up: Could you use search pruning to make your solution faster with a larger board?

Accepted
1,173,744
Submissions
2,929,480

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        ROW, COL = len(board), len(board[0])
        visited = set()
        def dfs(row, col, i):
            
            if (row >= ROW or col >= COL or row < 0 or col < 0 or (row,col) in visited or word[i] != board[row][col]):
                return False
            visited.add((row,col))
            if i == len(word)-1:
                return True
            
            ret_val = dfs(row+1, col, i+1) or dfs(row, col+1, i+1) or dfs(row-1,col,i+1) or dfs(row, col-1, i+1)
            
            visited.remove((row,col))
            return ret_val
        
        for row in range(ROW):
            for col in range(COL):
                if dfs(row, col, 0): return True
        return False
            
            
전체 404 / 5 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 549 명
  • 오늘 방문자 4,270 명
  • 어제 방문자 6,975 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,536 명
알림 0