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
.
题意:在矩阵中,相邻的元素可以是上、下、左、右的元素。同时要求矩阵中的同一个字符不能重复匹配。
思路:使用DFS遍历矩阵,直到遍历完字符串,说明匹配。但是需要记录矩阵中哪个字符是已经匹配过的。
由于英文字符范围是0~127,因此遍历某个字符后,进行c^=128操作,该字符在后续匹配中就不会再次
匹配到,从而实现标记的效果。在回溯的时候需要将标记的字符还原。
代码如下:
public boolean exist(char[][] board, String word) { for(int i=0; i<board.length; i++) { for(int j=0; j<board[0].length; j++) { if(exist(board, i, j, word, 0)) return true; } } return false; } public boolean exist(char[][] board, int x, int y, String word, int index) { if(index == word.length()) return true; if(x < 0 || y<0 || x>=board.length || y>=board[0].length || board[x][y] != word.charAt(index)) return false; board[x][y] ^= 128; boolean exist = exist(board, x-1, y, word, index+1) || exist(board, x+1, y, word, index+1) || exist(board, x, y-1, word, index+1) || exist(board, x, y+1, word, index+1) ; board[x][y] ^= 128; return exist; }
时间: 2024-10-17 14:17:24