这个是找到一种即可返回。那么可以双重便利,以任意一个位置i,j为起始点判断,开始上下左右遍历组成,每获取一个字符就匹配一次,匹配后的字符加个标记,下次不再匹配,相等则进行下一个元素获取。循环往复。代码如下:
- class Solution {
- public boolean exist(char[][] board, String word) {
- if (board==null||board[0]==null||word==null||word.isEmpty()){
- return false;
- }
- char[] chs = word.toCharArray();
- for (int i = 0; i < board.length; i++) {
- char[] chars = board[i];
- for (int j = 0; j < chars.length; j++) {
- if ( process(board,i,j,chs,0)){
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean process(char[][] board, int i, int j, char[] chs, int index) {
- if (index==chs.length){
- return true;
- }
- if (i<0||i==board.length||j<0||j==board[0].length){
- return false;
- }
- if (board[i][j]!=chs[index]){
- return false;
- }
- char temp = board[i][j];
- board[i][j]=0;
- boolean ans=process(board,i+1,j,chs,index+1)
- ||process(board,i-1,j,chs,index+1)
- ||process(board,i,j+1,chs,index+1)
- ||process(board,i,j-1,chs,index+1);
- board[i][j]=temp;
- return ans;
- }
- }