79. 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 are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

题目含义:给定一个字母组成的矩阵,看看相邻的字母能否组成一个给定的单词,每个位置的字母只能使用一次

 1     private boolean exist(char[][] board, int x, int y, char[] word, int i) {
 2         if (i == word.length) return true;
 3         if (x < 0 || y < 0 || x == board.length || y == board[x].length) return false;
 4         if (board[x][y] != word[i]) return false;
 5         board[x][y] ^= 256;    //将当前位置变得和任何字符都不相等,避免遍历周边4个节点的是否,又找到本节点
 6         boolean exist = exist(board, x, y + 1, word, i + 1)
 7                 || exist(board, x, y - 1, word, i + 1)
 8                 || exist(board, x + 1, y, word, i + 1)
 9                 || exist(board, x - 1, y, word, i + 1);
10         board[x][y] ^= 256;    //周边4个节点都遍历完了,可以恢复本节点了
11         return exist;
12     }
13     
14     public boolean exist(char[][] board, String word) {
15         char[] w = word.toCharArray();
16         for (int x = 0; x < board.length; x++) {
17             for (int y = 0; y < board[x].length; y++) {
18                 if (exist(board, x, y, w, 0)) return true;
19             }
20         }
21         return false;
22     }
原文地址:https://www.cnblogs.com/wzj4858/p/7676126.html