输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
提示:
1 <= board.length <= 200
1 <= board[i].length <= 200
2. 解法 - DFS
2.1 Java
classSolution {publicbooleanexist(char[][] board,String word) {// 字符串 - 字符数组char[] words =word.toCharArray();// 遍历所有字符,找到为止,没找到就返回falsefor(int i=0;i<board.length;i++){for(int j=0;j<board[0].length;j++){if(dfs(board, words, i, j,0))returntrue; } }returnfalse; }publicbooleandfs(char[][] board,char[] word,int i,int j,int index) {// 越界,矩阵当前字符不等于字符串当前字符,不合法,返回falseif (i <0|| i >=board.length|| j <0|| j >= board[0].length|| board[i][j] != word[index])returnfalse;// 矩阵当前字符=字符串当前字符,且已经是字符串最后一个字符,合法,返回trueif (index ==word.length-1)returntrue;// 记录下当前的字符,用于访问结束后恢复矩阵char curChar = board[i][j];// 已访问,标记为'/' board[i][j] ='/';// 上下左右都访问一下,只要有一条路成了就可以,所以用或boolean ans =dfs(board, word, i +1, j, index +1)||dfs(board, word, i -1, j, index +1)||dfs(board, word, i, j +1, index +1)||dfs(board, word, i , j -1, index +1);// 访问后还原矩阵 board[i][j] = curChar;// 返回结果return ans; }}
2.2 Kotlin
classSolution {funexist(board: Array<CharArray>, word: String): Boolean {// 字符串 - 字符数组val words = word.toCharArray()// 遍历所有字符,找到为止,没找到就返回falsefor (i in board.indices) {for (j in0 until board[0].size) {if (dfs(board, words, i, j, 0))returntrue } }returnfalse }fundfs(board: Array<CharArray>, word: CharArray, i: Int, j: Int, index: Int): Boolean {// 越界,矩阵当前字符不等于字符串当前字符,不合法,返回falseif (i <0|| i >= board.size || j <0|| j >= board[0].size || board[i][j] != word[index])returnfalse// 矩阵当前字符=字符串当前字符,且已经是字符串最后一个字符,合法,返回trueif (index == word.size -1)returntrue// 记录下当前的字符,用于访问结束后恢复矩阵val curChar = board[i][j]// 已访问,标记为'/' board[i][j] ='/'// 上下左右都访问一下,只要有一条路成了就可以,所以用或val ans =dfs(board, word, i +1, j, index +1) ||dfs(board, word, i -1, j, index +1) ||dfs(board, word, i, j +1, index +1) ||dfs(board, word, i, j -1, index +1)// 访问后还原矩阵 board[i][j] = curChar// 返回结果return ans }}