[LeetCode] 79. Word Search
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.
For example,
Given board =
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word =
"ABCB"
, -> returns false
.Thought process:
- Iterate through every character. For each character, if it matches the first character of word, change the character to a non-letter character to avoid it being reused, and do a DFS on it.
- Iterate through four directions (top, right, bottom, left). If any neighbor matches the next character of word, changed the character to 0, and do a DFS on that neighbor.
- Change the character back. If any neighbor returns true, return true. Otherwise return false.
- In the main loop, change the character back. Return true if any DFS returns true. Otherwise return false.
Solution:
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 | class Solution { private int[][] directions = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } }; public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (exist(board, word, i, j, 0)) { return true; } } } return false; } private boolean exist(char[][] board, String word, int row, int col, int index) { if (board[row][col] != word.charAt(index)) { return false; } if (index == word.length() - 1) { return true; } char temp = board[row][col]; board[row][col] = ' '; for (int i = 0; i < 4; i++) { int nextRow = row + directions[i][0]; int nextCol = col + directions[i][1]; if (nextRow >= 0 && nextRow < board.length && nextCol >= 0 && nextCol < board[0].length) { if (exist(board, word, nextRow, nextCol, index + 1)) { return true; } } } board[row][col] = temp; return false; } } |
Time complexity:
Say the board's height is a, width is b, and the word's length is c. The overall time complexity is O(abc).
Comments
Post a Comment