Skip to content

Latest commit

 

History

History
59 lines (48 loc) · 1.58 KB

79. Word Search.md

File metadata and controls

59 lines (48 loc) · 1.58 KB

79. Word Search

Problem

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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

tag:

  • bfs

Solution

以面板中的任一字符作为起始节点,进行深度优先搜索,如果匹配,返回True,如果所有节点的搜索结果均不匹配,返回false。

java

	public boolean exist(char[][] board, String word) {
		boolean isVisit[][] = 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 (search(board, isVisit, word, 0, i, j))
					return true;
		return false;
	}

	private boolean search(char[][] board, boolean[][] isVisit, String word, int index, int i, int j) {
		if (index == word.length())
			return true;
		if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isVisit[i][j]
				|| board[i][j] != word.charAt(index))
			return false;
		isVisit[i][j] = true;
		boolean result = search(board, isVisit, word, index + 1, i + 1, j)
				|| search(board, isVisit, word, index + 1, i - 1, j)
				|| search(board, isVisit, word, index + 1, i, j + 1)
				|| search(board, isVisit, word, index + 1, i, j - 1);
		isVisit[i][j] = false;
		return result;
	}

go