剑指12 矩阵中的路径

  1. class Solution {
  2. public boolean exist(char[][] board, String word) {
  3. if (board == null || word == null)
  4. return false;
  5. int[][] visited = new int[board.length][board[0].length];
  6. for (int i = 0; i < board.length; i++)
  7. for (int j = 0; j < board[0].length; j++)
  8. visited[i][j] = 0;
  9. int pathLength = 0;
  10. for (int i = 0; i < board.length; i++)
  11. for (int j = 0; j < board[0].length; j++)
  12. if (exitCore(board, word, i, j, visited, pathLength))
  13. return true;
  14. return false;
  15. }
  16. private boolean exitCore(char[][] board, String word, int i, int j, int[][] visited, int pathLength) {
  17. if (pathLength == word.length())
  18. return true;
  19. boolean exist = false;
  20. if (i >= 0 && i < board.length && j >= 0 && j < board[0].length && board[i][j] == word.charAt(pathLength) && visited[i][j] == 0) {
  21. ++pathLength;
  22. visited[i][j] = 1;
  23. exist = exitCore(board, word, i + 1, j, visited, pathLength) || exitCore(board, word, i - 1, j, visited, pathLength) || exitCore(board, word, i, j - 1, visited, pathLength) || exitCore(board, word, i, j + 1, visited, pathLength);
  24. if (!exist) {
  25. --pathLength;
  26. visited[i][j] = 0;
  27. }
  28. }
  29. return exist;
  30. }
  31. }