leetcode Word Search

回溯也刷完了,再从头总结一下,照例从简到难。

 Word Search 原题地址:

https://oj.leetcode.com/problems/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 .

先找首字母,然后在该字母邻居中找下一个字母,注意board里每个字母只能最多使用一次。

public class Solution {
    public boolean exist(char[][] board, String word) {
		if (word == null || word.length() == 0)
			return false;
		int row = board.length;
		int column = board[0].length;
		boolean[][] path = new boolean[row][column];
		
        for (int i = 0; i < row; i++)
        	for (int j = 0; j < column; j++) {
        		if (board[i][j] == word.charAt(0)) {
        			path[i][j] = true;
        			if (word.length()==1 || exist(board, word.substring(1), path, i, j))
        				return true;
        			path[i][j] = false;
        		}
        	}
        return false;
    }
	
	private boolean exist(char[][] board, String word,boolean[][] path, int i, int j) {
		if (word.length() == 0)
			return true;
		int row = board.length;
		int column = board[0].length;
		
		int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
		
		for (int d = 0; d < direction.length; d++) {
			int _i = i + direction[d][0];
			int _j = j + direction[d][1];
			
			if (_i >= 0 && _i < row && _j >= 0 && _j < column && board[_i][_j] == word.charAt(0) && !path[_i][_j]) {
				path[_i][_j] = true;
				if (word.length() == 1 || exist(board, word.substring(1), path, _i, _j))
					return true;
				path[_i][_j] = false;
			}
		}
		return false;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值