Advertisement
vladimirVenkov

wordSearch79

Jun 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. class Solution {
  2.     public boolean exist(char[][] board, String word) {
  3.         return obhod (board, word);
  4.     }
  5.     static boolean obhod(char[][] matrix, String word) {
  6.         boolean isFound = false;
  7.         boolean[][] visited = new boolean[matrix.length][matrix[0].length];
  8.         for (int i = 0; i < matrix.length; i++) {
  9.             for (int j = 0; j < matrix[0].length; j++) {
  10.                 if(matrix[i][j] == word.charAt(0)) isFound = isGood(matrix, visited, word, i, j, 0) ;
  11.                 if(isFound) return isFound;
  12.             }
  13.         }
  14.         return false;
  15.     }
  16.  
  17.     static boolean isGood(char[][] matrix, boolean[][] visited, String word, int row, int col, int letter) {
  18.         if ( row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length ) return  false;
  19.         if(matrix[row][col] != word.charAt(letter) || visited[row][col] ) return false;
  20.         if(matrix[row][col] == word.charAt(letter) && letter == word.length() - 1) return true;
  21.         visited[row][col] = true;
  22.         if(isGood(matrix, visited, word, row, col + 1, letter + 1)) return true;
  23.         if(isGood(matrix, visited, word,  row + 1, col, letter + 1)) return true;
  24.         if(isGood(matrix, visited, word, row, col - 1, letter + 1)) return true;
  25.         if(isGood(matrix, visited, word, row - 1, col, letter + 1)) return true;
  26.         visited[row][col] = false;
  27.         return false;
  28.         }
  29.  
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement