Created
December 1, 2013 04:44
-
-
Save charlespunk/7728593 to your computer and use it in GitHub Desktop.
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. | |
For example, | |
Given board = | |
[ | |
["ABCE"], | |
["SFCS"], | |
["ADEE"] | |
] | |
word = "ABCCED", -> returns true, | |
word = "SEE", -> returns true, | |
word = "ABCB", -> returns false. |
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
public class Solution { | |
public boolean exist(char[][] board, String word) { | |
if(word.length() == 0) return true; | |
for(int i = 0; i < board.length; i++){ | |
for(int j = 0; j < board[0].length; j++){ | |
if(exist(board, i, j, word, 0)) return true; | |
} | |
} | |
return false; | |
} | |
public boolean exist(char[][] board, int x, int y, String word, int index){ | |
if(board[x][y] == word.charAt(index)){ | |
if(index == word.length() - 1) return true; | |
char c = board[x][y]; | |
board[x][y] = ' '; | |
if(x > 0 && exist(board, x - 1, y, word, index + 1)) return true; | |
if(x < board.length - 1 && exist(board, x + 1, y, word, index + 1)) return true; | |
if(y > 0 && exist(board, x, y - 1, word, index + 1)) return true; | |
if(y < board[0].length - 1 && exist(board, x, y + 1, word, index + 1)) return true; | |
board[x][y] = c; | |
return false; | |
} | |
else return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment