首页 > 其他 > 详细

[LeetCode 79] Word Search

时间:2015-04-03 09:18:57      阅读:314      评论:0      收藏:0      [点我收藏+]

题目链接: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"));

	}

}


[LeetCode 79] Word Search

原文:http://blog.csdn.net/ever223/article/details/44841719

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!