Title Link: 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 is those horizontally or V Ertically neighboring. The same letter cell is used more than once. For Example,given Board =[["ABCE"], ["SFCs"], ["Adee"]]word = "abcced", returns True,word = "See", returns True,word = "ABCB", returns false. * */public class Wordsearch {//83/83 test Cases passed.//status:accepted//runtime:313 ms//submitted:0 minutes ago//a bit Surprise, two times on AC, ^_^//backtracking//Time complexity O (n ^ 2) space complexity O (n ^ 2) public Boolean isexist = False;public boolean[][] used; public boolean exist (char[][] board, String word) {int m = board.length; int n = board[0].length; used = new boolean[m][n];//used to mark whether the position character has been used for (int i = 0; i < m; i++) {for (int j = 0; J < N; j + +) {Used[i][j] = f Alse;}} for (int i = 0, i < m; i++) {for (int j = 0; J < N; j + +) {if (!isexist) {exist (board, I, J, Word, 0);} else {return isexist;}}} return isexist; } public void exist (char[][] board, int m, int n, String word, int z) {if (z = = Word.length ()) Isexist = True;if (isexist || M < 0 | | M >= Board.length | | N < 0 | | N >= board[0].length) {return;} if (!used[m][n] && board[m][n] = = Word.charat (z)) {//token used used[m][n] = true; Search left with order-independent exist (board, M, n-1, Word, z + 1);//Search up exist (board, M-1, N, Word, z + 1);//Search down exist (board, M + 1, N, wor D, z + 1);//Search Right exist (board, M, n + 1, Word, z + 1);//unmark used[m][n] = false; }}public static void Main (string[] args) {char[][] board = new char[][] {{' A ', ' B ', ' C ', ' E '},{' s ', ' F ', ' C ', ' s '},{' A ', ' D ', ' e ', ' e '}; System.out.println (New Wordsearch (). exist (board, "abcced")); System.out.println (New Wordsearch (). exist (board, "see")); System.out.println (New Wordsearch (). exist (board, "ABCB"));}}
[Leetcode 79] Word Search