LeetCode 79
https://leetcode-cn.com/problems/word-search/
这个题没啥好说的,从每个字母开始去DFS看是不是可以找得到同样内容的字符串,但是在实现的细节上还是有很多需要改进的地方。
首先先上自己的代码
class Solution { public boolean exist(char[][] board, String word) { if(board == null || board.length == 0 || word == null || word.length() == 0){ return false; } int[][] direction = new int[][]{{-1,0},{1,0},{0,-1},{0,1}}; boolean[][] visited = new boolean[board.length][board[0].length]; for(int i = 0;i < board.length;i++){ for(int j = 0; j < board[i].length;j++){ if(travel(board, word, 0, visited, direction, i, j)){ return true; } } } return false; } private boolean travel(char[][] board, String word, int pos, boolean[][] visited, int[][] direction,int i , int j){ if(i<0||i>=board.length || j<0 || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(pos)){ return false; } if(pos == word.length()-1){ return true; } visited[i][j] = true; boolean flag = false; for(int k = 0; k< 4;k++){ int newX = i+direction[k][0]; int newY = j+direction[k][1]; flag = travel(board, word, pos + 1, visited, direction, newX, newY) || flag; } if(!flag){ visited[i][j] = false; } return flag; } }
可以看到我用到visited数组来记录是否访问过。
再贴其他人的代码
class Solution { public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++){ for (int j = 0; j < board[0].length; j++) { if (search(board, word, i, j, 0)) { return true; } } } return false; } boolean search(char[][] board, String word, int i, int j, int k) { if (k >= word.length()) return true; if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(k)) return false; board[i][j] += 256; boolean result = search(board, word, i - 1, j, k + 1) || search(board, word, i + 1, j, k + 1) || search(board, word, i, j - 1, k + 1) || search(board, word, i, j + 1, k + 1); board[i][j] -= 256; return result; } }
他的代码里去掉了visited数组,减少了内存的开销,加快程序的运行速度,太顶了这个复用board数组的方法!!!!