Last active
October 26, 2018 06:47
-
-
Save hsaputra/8ee17b0bfa274f42658d226555f9db21 to your computer and use it in GitHub Desktop.
Word Search - https://leetcode.com/problems/word-search/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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. | |
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. | |
**/ | |
class Solution { | |
public boolean exist(char[][] board, String word) { | |
for (int i = 0; i < board.length; i++) { | |
for (int j = 0; j < board[i].length; j++) { | |
boolean[][] visited = new boolean[board.length][board[0].length]; | |
if (search(board, word, 0, i, j, visited)) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
private boolean search(char[][] board, String word, int word_i, int i, int j, boolean[][] visited) { | |
if (word_i == word.length()) { | |
return true; | |
} | |
if (i < 0 || j < 0 || i >= board.length || j >= board[i].length) { | |
return false; | |
} | |
if (visited[i][j]) { | |
return false; | |
} | |
if (word.charAt(word_i) != board[i][j]) { | |
return false; | |
} | |
visited[i][j] = true; | |
boolean existed = | |
search(board, word, word_i + 1, i + 1, j, visited) || | |
search(board, word, word_i + 1, i - 1, j, visited) || | |
search(board, word, word_i + 1, i, j + 1, visited) || | |
search(board, word, word_i + 1, i, j - 1, visited); | |
visited[i][j] = false; | |
return existed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.