Advertisement
ogv

Untitled

ogv
Aug 9th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. /*
  2. Runtime: 7 ms
  3. Memory Usage: 38.3 MB
  4. */
  5. class Solution {
  6.     public boolean exist(char[][] board, String word) {
  7.         if (board.length == 0 || board[0].length == 0) {
  8.             return false;
  9.         }
  10.         if (word == null || word.length() == 0) {
  11.             return false;
  12.         }
  13.        
  14.         boolean[][] visited = new boolean[board.length][board[0].length];
  15.        
  16.         for (int r = 0; r < board.length; r++)
  17.             for (int c = 0; c < board[r].length; c++ ) {
  18.                 visited[r][c] = false;
  19.             }
  20.        
  21.        
  22.         for (int r = 0; r < board.length; r++)
  23.             for (int c = 0; c < board[r].length; c++ ) {
  24.                 if (exist(board, word, 0, r, c, visited)) {
  25.                     return true;
  26.                 }
  27.             }
  28.        
  29.         return false;
  30.     }
  31.    
  32.     public boolean exist(char[][] board, String word, int pos, int r, int c, boolean[][] visited) {
  33.         if (board[r][c] != word.charAt(pos)) {
  34.             return false;
  35.         }
  36.        
  37.         if (pos == word.length() - 1) {
  38.             return true;
  39.         }
  40.        
  41.         int[][] next = new int[][] {
  42.             { r, c + 1 },
  43.             { r, c - 1},
  44.             { r + 1, c },
  45.             { r - 1, c }
  46.         };
  47.        
  48.         visited[r][c] = true;
  49.        
  50.         for (int i = 0; i < 4; i++) {            
  51.             int newR = next[i][0];
  52.             int newC = next[i][1];
  53.  
  54.             if (newR < 0 || newR >= board.length || newC < 0 || newC >= board[0].length) {
  55.                 continue;
  56.             }
  57.            
  58.             if (visited[newR][newC]) {
  59.                 continue;
  60.             }
  61.  
  62.             if (exist(board, word, pos + 1, newR, newC, visited)) {
  63.                 return true;
  64.             }
  65.         }
  66.        
  67.         visited[r][c] = false;
  68.                
  69.         return false;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement