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

Word Search

时间:2014-09-17 23:26:03      阅读:388      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   算法   

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 {
    boolean [][]visit;
    char[][]board;
    int ROW;
    int COL;
    public boolean exist(int row,int col,String word)
    {
        if(board[row][col]!=word.charAt(0))
        {
            return false;
        }
        if(word.length()==1)
        {
            return true;
        }
        boolean result=false;
        visit[row][col]=true;
        String remaining=word.substring(1);
        if(row>0&&!visit[row-1][col])
        {
            result=exist(row-1,col,remaining);
        }
        if(!result&&row<ROW-1&&!visit[row+1][col])
        {
            result=exist(row+1,col,remaining);
        }
        if(!result&&col>0&&!visit[row][col-1])
        {
            result=exist(row,col-1,remaining);
        }
        if(!result&&col<COL-1&&!visit[row][col+1])
        {
            result=exist(row,col+1,remaining);
        }
        visit[row][col]=false;
        return result;
        
    }
    public boolean exist(char[][] board, String word) {
        if(word==null||word.length()==0)
        {
            return true;
        }
        if(board==null)
        {
            return false;
        }
        this.board=board;
        ROW=board.length;
        COL=board[0].length;
        visit=new boolean[ROW][COL];
        for(int i=0;i<ROW;i++)
        {
            for(int j=0;j<COL;j++)
            {
                visit[i][j]=false;
            }
        }
        for(int i=0;i<ROW;i++)
        {
            for(int j=0;j<COL;j++)
            {
                if(exist(i,j,word)){
                        return true;
                }
            }
        }
        return false;
    }
}


Word Search

标签:algorithm   leetcode   算法   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39348849

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