79. Word Search[Medium]

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Example
image

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

思路

题解

    public boolean exist(char[][] board, String word) {
       
       for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (dfsExist(i, j, board, 0, word.toCharArray(), new boolean[board.length][board[0].length]))
                    return true;
            }
        }
        return false;
    }

    public boolean dfsExist(int row, int column, char[][] board, int index, char[] words, boolean[][] path) {
        if (row < 0 || row >= board.length || column < 0 || column >= board[0].length
                || board[row][column] != words[index]
                || path[row][column])
            return false;
	// 结束条件,通过上面的if条件,然后index又到了string的最后一位,符合条件
        if (index == words.length - 1)
            return true;

        path[row][column] = true;
        boolean res = dfsExist(row, column + 1, board, index + 1, words, path) ||
                dfsExist(row, column - 1, board, index + 1, words, path) ||
                dfsExist(row + 1, column, board, index + 1, words, path) ||
                dfsExist(row - 1, column, board, index + 1, words, path);
        path[row][column] = false;
        return res;
    }
posted @ 2023-02-20 19:55  AaronTanooo  阅读(25)  评论(0)    收藏  举报