首页 > 其他 > 详细

Word Search

时间:2015-07-04 02:09:40      阅读:267      评论:0      收藏:0      [点我收藏+]

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.

?

public class Solution {
    public boolean exist(char[][] board, String word) {
        int rows = board.length;
        int cols = board[0].length;
        boolean[][] visit = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
        	for (int j = 0; j < cols; j++) {
        		if (dfs(board, word, 0, i, j, visit)) {
        			return true;
        		}
        	}
        }
        return false;
    }

	private boolean dfs(char[][] board, String word, int cnt, int rowindex, int colindex,
			boolean[][] visit) {
		if (cnt == word.length()) {
			return true;
		}
		if (rowindex < 0 || colindex < 0 || rowindex >= board.length || colindex >= board[0].length) {
			return false;
		}
		if (visit[rowindex][colindex])  {
			return false;
		}
		if (board[rowindex][colindex] != word.charAt(cnt)) {
			return false;
		}
		visit[rowindex][colindex] = true;
		boolean res = (dfs(board, word, cnt+1, rowindex+1, colindex, visit)
				|| dfs(board, word, cnt+1, rowindex, colindex+1, visit)
				|| dfs(board, word, cnt+1, rowindex-1, colindex, visit)
				|| dfs(board, word, cnt+1, rowindex, colindex-1, visit));
		visit[rowindex][colindex] = false;
		return res;
	}
}

?

Word Search

原文:http://hcx2013.iteye.com/blog/2223987

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!