Home LeetCode - 79. Word Search
Post
Cancel

LeetCode - 79. Word Search

79. Word Search - medium

문제

Given a 2D board and a word, find if the word exists in the grid.

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

제한사항

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

풀이

  • Back Tracking, DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
    bool backTracking(std::string& word, int wordIndex, vector<vector<char>>& board, int i, int j) {
        if (wordIndex >= word.size()) {
            return true;
        }
        
        if ((0 > i || i >= height) ||
            (0 > j || j >= width) ||
            wordIndex >= word.size() ||
            board[i][j] != word[wordIndex]) {
            return false;
        }
        
        char temp = board[i][j];
        board[i][j] = '0';
            
        bool res = backTracking(word, wordIndex + 1, board, i + 1, j) ||
                   backTracking(word, wordIndex + 1, board, i - 1, j) ||
                   backTracking(word, wordIndex + 1, board, i, j + 1) ||
                   backTracking(word, wordIndex + 1, board, i, j - 1);
    
        board[i][j] = temp;

        return res;
    }
    
    bool exist(vector<vector<char>>& board, string word) {
        height = board.size();
        width = board[0].size();
        
        for (int i = 0 ; i < height ; ++i) {
            for (int j = 0 ; j < width ; ++j) {                
                if(backTracking(word, 0, board, i, j)) {
                    return true;
                }
            }
        }
        
        return false;
    }
private:
    int height;
    int width;
};
This post is licensed under CC BY 4.0 by the author.