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
Given board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
DFS - with additional space for visited[][] matrix (12ms 52.97% AC)
classSolution {publicbooleanexist(char[][] board,String word) {if (board ==null||board.length==0|| board[0].length==0) {returnfalse; }if (word.length() ==0) {returntrue; }int M =board.length;int N = board[0].length;boolean[][] visited=newboolean[M][N];for (int i =0; i < M; i++) {for (int j =0; j < N; j++) {if (existHelper(board, visited, i, j, word,0)) returntrue; } }returnfalse; }privatebooleanexistHelper(char[][] board,boolean[][] visited,int row,int col,String word,int index) {if (index ==word.length()) returntrue;if (row <0|| col <0|| row >=board.length|| col >= board[0].length) returnfalse;if (word.charAt(index) != board[row][col] || visited[row][col]) returnfalse; visited[row][col] =true;int[] dx =newint[] {0,1,0,-1};int[] dy =newint[] {1,0,-1,0};for (int i =0; i <dx.length; i++) {if ( existHelper(board, visited, row + dx[i], col + dy[i], word, index +1)) {returntrue; } } visited[row][col] =false;returnfalse; }}
DFS - using temporary '#' mark visited element (15 ms 36.92% AC)
publicclassSolution { /** * @param board: A list of lists of character * @param word: A string * @return: A boolean */publicbooleanexist(char[][] board,String word) {if (board ==null||board.length==0|| board[0].length==0) {returnfalse; }if (word.length() ==0) {returntrue; }for (int i =0; i <board.length; i++) {for (int j =0; j < board[0].length; j++) {if (board[i][j] ==word.charAt(0)) {boolean result =dfs(board, word, i, j,0);if (result) {returntrue; } } } }returnfalse; }privatebooleandfs(char[][] board,String word,int i,int j,int k) {if (board ==null||board.length==0|| board[0].length==0) {returnfalse; }if (word.length() ==0) {returntrue; }if (word.length() == k) {returntrue; }boolean result =false;if (insideBoard(board, i, j)&& board[i][j] ==word.charAt(k)) {char temp = board[i][j]; board[i][j] ='#'; result =dfs(board, word, i +1, j, k +1)||dfs(board, word, i -1, j, k +1)||dfs(board, word, i, j +1, k +1)||dfs(board, word, i, j -1, k +1); board[i][j] = temp; }return result; }privatebooleaninsideBoard(char[][] board,int i,int j) {return (i >=0&& i <board.length&& j >=0&& j < board[0].length); }}