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.數組
給定一個board字符矩陣,能夠從任意一個點開始通過上下左右的方式走,每一個點只能走一次,若是存在一條路走過的字符等於給定的字符串,那麼返回truespa
以每個點做爲起點,使用回溯法進行搜索.net
算法實現類code
public class Solution { public boolean exist(char[][] board, String word) { // 【注意咱們假定輸入的參數都是合法】 // 訪問標記矩陣,初始值默認會設置爲false boolean[][] visited = new boolean[board.length][board[0].length]; // 以每個位置爲起點進行搜索,找到一個路徑就中止 for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (search(board, visited, i, j, word, new int[]{0})) { return true; } } } return false; } /** * @param board 字符矩陣 * @param visited 訪問標記矩陣 * @param row 訪問的行號 * @param col 訪問的列號 * @param word 匹配的字符串 * @param idx 匹配的位置,取數組是更新後的值能夠被其它引用所見 * @return */ private boolean search(char[][] board, boolean[][] visited, int row, int col, String word, int[] idx) { // 若是搜索的位置等於字串的長度,說明已經找到找到匹配的了 if (idx[0] == word.length()) { return true; } boolean hasPath = false; // 當前位置合法 if (check(board, visited, row, col, word, idx[0])) { // 標記位置被訪問過 visited[row][col] = true; idx[0]++; // 對上,右,下,左四個方向進行搜索 hasPath = search(board, visited, row - 1, col, word, idx ) // 上 || search(board, visited, row, col + 1, word, idx) // 右 || search(board, visited, row + 1, col, word, idx) // 下 || search(board, visited, row, col - 1, word, idx); // 左 // 若是沒有找到路徑就回溯 if (!hasPath) { visited[row][col] = false; idx[0]--; } } return hasPath; } /** * 斷定訪問的位置是否合法 * * @param board 字符矩陣 * @param visited 訪問標記矩陣 * @param row 訪問的行號 * @param col 訪問的列號 * @param word 匹配的字符串 * @param idx 匹配的位置 * @return */ public boolean check(char[][] board, boolean[][] visited, int row, int col, String word, int idx) { return row >= 0 && row < board.length // 行號合法 && col >= 0 && col < board[0].length // 列號合法 && !visited[row][col] // 沒有被訪問過 && board[row][col] == word.charAt(idx); // 字符相等 } }