码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Word Search

时间:2014-07-07 13:15:02      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

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.

https://oj.leetcode.com/problems/word-search/

 

思路:4个方向dfs,

 

bubuko.com,布布扣
public class Solution {
    public boolean exist(char[][] board, String word) {
        if (word == null || board == null || word.equals(""))
            return false;

        int m = board.length;
        int n = board[0].length;
        boolean visit[][] = new boolean[m][n];

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                boolean res = dfs(board, visit, i, j, word, 0);
                if (res)
                    return true;
            }

        return false;

    }

    private int offset[][] = new int[][] { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };

    private boolean dfs(char[][] board, boolean[][] visit, int x, int y, String word, int cur) {
        // System.out.println("dfs:"+x+","+y+","+cur);

        if (board[x][y] != word.charAt(cur))
            return false;

        if (cur == word.length() - 1) {
            return true;
        }

        int m = board.length;
        int n = board[0].length;

        visit[x][y] = true;
        int nx, ny;
        for (int i = 0; i < 4; i++) {
            nx = x + offset[i][0];
            ny = y + offset[i][1];

            if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
                boolean res = dfs(board, visit, nx, ny, word, cur + 1);
                if (res)
                    return true;
            }

        }
        visit[x][y] = false;

        return false;

    }

    public static void main(String[] args) {
        char[][] board;
        String word;
        board = new char[][] { { ‘A‘, ‘B‘, ‘C‘, ‘E‘ }, { ‘S‘, ‘F‘, ‘C‘, ‘S‘ }, { ‘A‘, ‘D‘, ‘E‘, ‘E‘ } };
        word = "ASA";
        System.out.println(new Solution().exist(board, word));

        board = new char[][] { { ‘b‘ } };
        word = "b";
        System.out.println(new Solution().exist(board, word));

    }

}
View Code

 

 

 

 

[leetcode] Word Search,布布扣,bubuko.com

[leetcode] Word Search

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3815486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!