Advertisement
ogv

Untitled

ogv
Aug 9th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. class Solution {
  2.     public boolean exist(char[][] board, String word) {
  3.         if (board.length == 0 || board[0].length == 0) {
  4.             return false;
  5.         }
  6.         if (word == null || word.length() == 0) {
  7.             return false;
  8.         }
  9.        
  10.         for (int r = 0; r < board.length; r++)
  11.             for (int c = 0; c < board[r].length; c++ ) {
  12.                 if (exist(board, word, 0, r, c, -1, -1)) {
  13.                     return true;
  14.                 }
  15.             }
  16.        
  17.         return false;
  18.     }
  19.    
  20.     public boolean exist(char[][] board, String word, int pos, int r, int c, int fromR, int fromC) {      
  21.         if (pos >= word.length()) {
  22.             return true;
  23.         }
  24.                        
  25.         if (board[r][c] != word.charAt(pos)) {
  26.             return false;
  27.         }            
  28.        
  29.         int[][] next = new int[][] {
  30.             { r + 1, c },
  31.             { r - 1, c },
  32.             { r, c - 1 },
  33.             { r, c + 1 }
  34.         };
  35.        
  36.         for (int i = 0; i < 4; i++) {            
  37.             int newR = next[i][0];
  38.             int newC = next[i][1];
  39.  
  40.             if (newR == fromR && newC == fromC) {
  41.                 continue;
  42.             }
  43.  
  44.             if (newR < 0 || newR >= board.length || newC < 0 || newC <= board[r].length) {
  45.                 continue;
  46.             }
  47.  
  48.             if (exist(board, word, pos + 1, newR, newC, r, c)) {
  49.                 return true;
  50.             }
  51.         }
  52.                
  53.         return false;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement