程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode | Word Search

LeetCode | Word Search

編輯:C++入門知識

題目

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.

分析

矩陣搜索的一般就考慮BFS或DFS了,BFS的方法寫起來代碼較長,是要紀錄每一層符合條件的元素的位置信息。這裡給出的是DFS的,其實就是非遞歸不好寫,寫個遞歸的了。

代碼

public class WordSearch {
	private char[] wordCharArray;
	private int L;
	private char[][] board;
	private int M;
	private int N;
	private boolean[][] mark;

	public boolean exist(char[][] board, String word) {
		if (word == null || word.length() == 0 || board == null
				|| board.length == 0) {
			return false;
		}
		wordCharArray = word.toCharArray();
		L = wordCharArray.length;
		this.board = board;
		M = board.length;
		N = board[0].length;
		mark = new boolean[M][N];
		for (int i = 0; i < M; ++i) {
			for (int j = 0; j < N; ++j) {
				if (dfs(i, j, 0)) {
					return true;
				}
			}
		}
		return false;
	}

	private boolean dfs(int i, int j, int k) {
		if (i < 0 || j < 0 || i >= M || j >= N || mark[i][j]) {
			return false;
		}
		if (board[i][j] != wordCharArray[k]) {
			return false;
		}
		if (k == L - 1) {
			return true;
		}
		mark[i][j] = true;
		boolean result = dfs(i - 1, j, k + 1) || dfs(i + 1, j, k + 1)
				|| dfs(i, j - 1, k + 1) || dfs(i, j + 1, k + 1);
		mark[i][j] = false;
		return result;
	}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved