LeetCode Word Search

来源:互联网 发布:手机荧光灯软件 编辑:程序博客网 时间:2024/06/13 00:07

Description:

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.

Solution:

一开始题目理解有误,没想到是DFS。不过LeetCode一直被人诟病的问题就是没有数据范围了。也导致了我想复杂了,以为是字符串题目了……囧

不过既然DFS可以解决的话,那么基本就是最普通的解决方案了,因为只是上下左右移动,实际上比经典问题“骑士周游”简单很多,虽说二者本质一样,大家感兴趣可以做做。

import java.util.*;public class Solution {int[][] direction = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };boolean[][] vis;int n, m;String word;char[][] board;public boolean exist(char[][] board, String word) {this.board = board;this.word = word;m = board.length;n = board[0].length;vis = new boolean[m][n];for (int i = 0; i < m; i++)Arrays.fill(vis[i], false);for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (dfs(i, j, 0))return true;return false;}boolean dfs(int i, int j, int index) {// 当前的index必须和word matchif (word.charAt(index) != board[i][j])return false;// 不可以实现走过if (vis[i][j])return false;if (index + 1 == word.length())return true;vis[i][j] = true;int ti, tj;for (int d = 0; d < 4; d++) {ti = i + direction[d][0];tj = j + direction[d][1];if (valid(ti, tj) && dfs(ti, tj, index + 1))return true;}vis[i][j] = false;return false;}boolean valid(int i, int j) {if (i >= 0 && i < m && j >= 0 && j < n)return true;return false;}}


0 0
原创粉丝点击