题目链接:word-search
/** * Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. * */ public class WordSearch { // 83 / 83 test cases passed. // Status: Accepted // Runtime: 313 ms // Submitted: 0 minutes ago //有点惊讶,两次就AC了,^_^ //回溯法 //时间复杂度O(n ^ 2) 空间复杂度O(n ^ 2) public boolean isExist = false; public boolean[][] used; public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; used = new boolean[m][n]; //用来标记该位置字符是否已用 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { used[i][j] = false; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (!isExist) { exist(board, i, j, word, 0); } else { return isExist; } } } return isExist; } public void exist(char[][] board, int m, int n, String word, int z) { if(z == word.length()) isExist = true; if( isExist || m < 0 || m >= board.length || n < 0 || n >= board[0].length) { return; } if(!used[m][n] && board[m][n] == word.charAt(z)) { //标记已用 used[m][n] = true; //向左搜索 与顺序无关 exist(board, m, n - 1, word, z + 1); //向上搜索 exist(board, m - 1, n, word, z + 1); //向下搜索 exist(board, m + 1, n, word, z + 1); //向右搜索 exist(board, m, n + 1, word, z + 1); //取消标记 used[m][n] = false; } } public static void main(String[] args) { char[][] board = new char[][] { {'A','B','C', 'E'}, {'S','F','C', 'S'}, {'A','D','E', 'E'}}; System.out.println(new WordSearch().exist(board, "ABCCED")); System.out.println(new WordSearch().exist(board, "SEE")); System.out.println(new WordSearch().exist(board, "ABCB")); } }
原文地址:http://blog.csdn.net/ever223/article/details/44841719