标签:dfs boolean res -- exists vertica int turn bool
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.
Given board =
[ "ABCE", "SFCS", "ADEE" ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
考察:DFS 递归---回溯
public class Solution { /** * @param board: A list of lists of character * @param word: A string * @return: A boolean */ public boolean exist(char[][] board, String word) { if (board == null || board.length == 0 || board[0].length == 0) { return false; } if (word.length() == 0) { return true; } boolean result = false; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { result = findWord(board, i, j, word, 0); if (result == true) { return true; } } } } return false; } private boolean findWord(char[][] board, int i, int j, String word, int start) { if (start == word.length()) { return true; } if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(start)) { return false; } board[i][j] = ‘#‘; boolean result = findWord(board, i - 1, j, word, start + 1) || findWord(board, i + 1, j , word, start + 1) || findWord(board, i, j - 1, word, start + 1) || findWord(board, i, j + 1, word, start + 1); board[i][j] = word.charAt(start); return result; } }
标签:dfs boolean res -- exists vertica int turn bool
原文地址:http://www.cnblogs.com/FLAGyuri/p/7183887.html