[LeetCode] 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 .


对于这种要找出所以可能解的问题,思路就两个字——回溯。

1) 一开始匹配第一个字符,找到所有可能的起始点位置。

2)对于每个位置,分别可以向上下左右四个方向进行深度遍历搜索。

	private boolean dfs(char[][] board, String word, int i, int j,
			boolean[][] visited) {
		// check board[i - 1][j]
		if (i - 1 >= 0 && visited[i - 1][j] == false
				&& board[i - 1][j] == word.charAt(0)) {
			if (word.length() == 1) {
				return true;
			} else {
				visited[i - 1][j] = true;
				if (dfs(board, word.substring(1), i - 1, j, visited))
					return true;
				// backtrack
				visited[i - 1][j] = false;
			}
		}

		// check board[i + 1][j]
		if (i + 1 < board.length && visited[i + 1][j] == false
				&& board[i + 1][j] == word.charAt(0)) {
			if (word.length() == 1) {
				return true;
			} else {
				visited[i + 1][j] = true;
				if (dfs(board, word.substring(1), i + 1, j, visited))
					return true;
				// backtrack
				visited[i + 1][j] = false;
			}
		}

		// check board[i][j - 1]
		if (j - 1 >= 0 && visited[i][j - 1] == false
				&& board[i][j - 1] == word.charAt(0)) {
			if (word.length() == 1) {
				return true;
			} else {
				visited[i][j - 1] = true;
				if (dfs(board, word.substring(1), i, j - 1, visited))
					return true;
				// backtrack
				visited[i][j - 1] = false;
			}
		}

		// check board[i][j + 1]
		if (j + 1 < board[0].length && visited[i][j + 1] == false
				&& board[i][j + 1] == word.charAt(0)) {
			if (word.length() == 1) {
				return true;
			} else {
				visited[i][j + 1] = true;
				if (dfs(board, word.substring(1), i, j + 1, visited))
					return true;
				// backtrack
				visited[i][j + 1] = false;
			}
		}

		return false;
	}

	public boolean exist(char[][] board, String word) {
		if (board.length == 0 || word.length() == 0)
			return true;

		boolean[][] visited = new boolean[board.length][board[0].length];

		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				if (board[i][j] == word.charAt(0)) {
					if (word.length() == 1) {
						return true;
					} else {
						visited[i][j] = true;
						if (dfs(board, word.substring(1), i, j, visited))
							return true;
						// backtrack
						visited[i][j] = false;
					}
				}
			}
		}

		return false;
	}
代码写得比较冗余,dfs方法里有很多重复代码,其实可以弄一个数组,把四个方向的位移给写进去,这样代码会更精简。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值