題目
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
,"SEE"
,
-> returns true
,"ABCB"
,
-> returns false
.分析
矩陣搜索的一般就考慮BFS或DFS了,BFS的方法寫起來代碼較長,是要紀錄每一層符合條件的元素的位置信息。這裡給出的是DFS的,其實就是非遞歸不好寫,寫個遞歸的了。
代碼
public class WordSearch { private char[] wordCharArray; private int L; private char[][] board; private int M; private int N; private boolean[][] mark; public boolean exist(char[][] board, String word) { if (word == null || word.length() == 0 || board == null || board.length == 0) { return false; } wordCharArray = word.toCharArray(); L = wordCharArray.length; this.board = board; M = board.length; N = board[0].length; mark = new boolean[M][N]; for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { if (dfs(i, j, 0)) { return true; } } } return false; } private boolean dfs(int i, int j, int k) { if (i < 0 || j < 0 || i >= M || j >= N || mark[i][j]) { return false; } if (board[i][j] != wordCharArray[k]) { return false; } if (k == L - 1) { return true; } mark[i][j] = true; boolean result = dfs(i - 1, j, k + 1) || dfs(i + 1, j, k + 1) || dfs(i, j - 1, k + 1) || dfs(i, j + 1, k + 1); mark[i][j] = false; return result; } }