[LeetCode]Word Search
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]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 =
[ [‘A‘,‘B‘,‘C‘,‘E‘], [‘S‘,‘F‘,‘C‘,‘S‘], [‘A‘,‘D‘,‘E‘,‘E‘] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
题目的意思很明白了,一般的搜索题,剪枝下就好,不过这题我刚开始做的时候比较笨,开了块内存boolea[][] visited来标记是访问,但是忘记了数据比较多的时候每次的寻址时间开销很大。导致TLE了,经过改进,使用了标记-复原的方法,就省了新开辟内存的开销了。
(注意:需要复原原始访问位,不然当访问失败时,下次访问的时候就没得搞了。)
上代码了。
import java.util.Scanner; public class Solution { public boolean exist( char[][] board, String word ) { char c = word.charAt( 0 ); for( int i = 0; i < board.length; i++ ) { for( int j = 0; j < board[ i ].length; j++ ) { if( board[ i ][ j ] == c ) { if(search( i, j, board, word, 0 )) { return true; } } } } return false; } public boolean search( int x, int y, char[][] board, String word, int k) { if( k>=word.length() ) { return true; } if(x < 0 || x >= board.length || y < 0 || y >= board[ 0 ].length){ return false; } char ch = word.charAt( k ); if(ch == board[x][y]){ board[x][y] = ‘*‘; if(search( x+1, y, board, word, k+1 ) || search( x-1, y, board, word, k+1 ) || search( x, y+1, board, word, k+1 ) || search( x, y-1, board, word, k+1 )){ return true; } board[x][y] = ch; } return false; } public static void main( String[] args ) { // TODO Auto-generated method stub Solution s = new Solution(); Scanner sc = new Scanner( System.in ); String word = "ghi"; while( sc.hasNext() ) { int w = sc.nextInt(); int h = sc.nextInt(); char[][] board = new char[ w ][ h ]; for( int i = 0; i < w; i++ ) { for( int j = 0; j < h; j++ ) { String temp = sc.next(); board[ i ][ j ] = temp.charAt( 0 ); } } System.out.println( s.exist( board, word ) ); } } /* * 3 3 a b c d e f g h i 4 4 a b c d e f g h i j k l m n o p */
以上是关于[LeetCode]Word Search的主要内容,如果未能解决你的问题,请参考以下文章
leetcode笔记:Maximum Product of Word Lengths