这道题自己完成的,不难。
回溯。
public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; int wordLength = word.length(); if(word.length()>m*n){ return false; } boolean[][] b = new boolean[m][n]; for(int i = 0;i<m;i++){ for(int j = 0;j<n;j++){ if(board[i][j] == word.charAt(0)){ b[i][j] = true; if(find(board,b,word,i,j,1,m,n,wordLength)){ return true; } b[i][j] = false; } } } return false; } private boolean find(char[][] board, boolean[][] b, String word, int i, int j, int k, int m, int n, int wordLength) { if(k == wordLength){ return true; } if(i+1<m){ if(!b[i+1][j] && board[i+1][j] == word.charAt(k)){ b[i+1][j] = true; if(find(board, b, word, i+1, j, k+1, m, n, wordLength)){ return true; } b[i+1][j] = false; } } if(i-1>=0){ if(!b[i-1][j] && board[i-1][j] == word.charAt(k)){ b[i-1][j] = true; if(find(board, b, word, i-1, j, k+1, m, n, wordLength)){ return true; } b[i-1][j] = false; } } if(j+1<n){ if(!b[i][j+1] && board[i][j+1] == word.charAt(k)){ b[i][j+1] = true; if(find(board, b, word, i, j+1, k+1, m, n, wordLength)){ return true; } b[i][j+1] = false; } } if(j-1>=0){ if(!b[i][j-1] && board[i][j-1] == word.charAt(k)){ b[i][j-1] = true; if(find(board, b, word, i, j-1, k+1, m, n, wordLength)){ return true; } b[i][j-1] = false; } } return false; }
待优化。
——2020.6.30