[LeetCode 79] Word Search

134 篇文章 0 订阅
49 篇文章 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"));

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值