xiutianxiudi

Lintcode 123. Word Search

Oct 2nd, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. public class Solution {
  2.  
  3.     private static final int[][] DELTA_DIMS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
  4.  
  5.     /**
  6.      * @param board: A list of lists of character
  7.      * @param word: A string
  8.      * @return: A boolean
  9.      */
  10.     public boolean exist(char[][] board, String word) {
  11.         if(word == null) {
  12.             return false;
  13.         }
  14.  
  15.         int m = (board == null) ? 0 : board.length;
  16.         int n = (m == 0) ? 0 : board[0].length;
  17.  
  18.         for(int i = 0; i < m; i++) {
  19.             for(int j = 0; j < n; j++) {
  20.                 if(exist(board, i, j, word, 0)) {
  21.                     return true;
  22.                 }
  23.             }
  24.         }
  25.         return false;
  26.     }
  27.  
  28.     private boolean exist(char[][] board, int x, int y, String word, int wordI) {
  29.         if(wordI == word.length()) {
  30.             return true;
  31.         }
  32.  
  33.         if(wordI > word.length()) {
  34.             return false;
  35.         }
  36.  
  37.         if(!inBound(board, x, y)) {
  38.             return false;
  39.         }
  40.  
  41.         if(board[x][y] != word.charAt(wordI)) {
  42.             return false;
  43.         }
  44.  
  45.         char origChar = board[x][y];
  46.         board[x][y] = 0;
  47.  
  48.         for(int[] deltaDim : DELTA_DIMS) {
  49.             int nx = x + deltaDim[0];
  50.             int ny = y + deltaDim[1];
  51.  
  52.             if(exist(board, nx, ny, word, wordI + 1)) {
  53.                 board[x][y] = origChar;
  54.                 return true;
  55.             }
  56.         }
  57.  
  58.         board[x][y] = origChar;
  59.         return false;
  60.     }
  61.  
  62.     private boolean inBound(char[][] board, int x, int y) {
  63.         int m = (board == null) ? 0 : board.length;
  64.         int n = (m == 0) ? 0 : board[0].length;
  65.  
  66.         return x >= 0 && x < m &&
  67.             y >= 0 && y < n;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment