标签: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,
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)); } }
[leetcode] Word Search,布布扣,bubuko.com
标签:style blog http color strong os
原文地址:http://www.cnblogs.com/jdflyfly/p/3815486.html