leetcode -- 79. Word Search

题目描述

题目难度:Medium
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.

Example:

board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

AC代码

leetcode 上优秀代码
link:https://leetcode.com/problems/word-search/discuss/27658/Accepted-very-short-Java-solution.-No-additional-space.

class Solution {
   public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y<board.length; y++) {
    	for (int x=0; x<board[y].length; x++) {
    		if (exist(board, y, x, w, 0)) return true;//尝试从二维数组的每一位开始匹配,若有成功的返回true,否则返回false。
    	}
    }
    return false;
}

private boolean exist(char[][] board, int y, int x, char[] word, int i) {
	if (i == word.length) return true; //完全匹配成功
	if (y<0 || x<0 || y == board.length || x == board[y].length) return false; //下标不存在
	if (board[y][x] != word[i]) return false; //和当前匹配的字符不相符
	board[y][x] ^= 256; //和当前匹配的字符相符,并使当前二维数组里面的字符“消失”,题目说明每个字符最多匹配一次
	boolean exist = exist(board, y, x+1, word, i+1)
		|| exist(board, y, x-1, word, i+1)
		|| exist(board, y+1, x, word, i+1)
		|| exist(board, y-1, x, word, i+1); //从当前二维数组元素的四周匹配word中的下一个字符
	board[y][x] ^= 256;// a ^ b ^ b == a;
	return exist;
}
}

你可能感兴趣的:(算法,leetcode)