zoukankan      html  css  js  c++  java
  • leetcode Word Search

    题目连接

    https://leetcode.com/problems/word-search/  

    Word Search

    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.

    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.

    const int dx[] = { 0, 0, -1, 1 }, dy[] = { -1, 1, 0, 0 };
    class Solution {
    public:
    	int n, H, W;
    	bool exist(vector<vector<char>>& board, string word) {
    		n = word.length();
    		H = board.size(), W = board[0].size();
    		queue<pair<int, int>>q;
    		for (int i = 0; i < H; i++) {
    			for (int j = 0; j < W; j++) {
    				if (word[0] == board[i][j]) {
    					vector<vector<bool>> vis(H, vector<bool>(W));
    					vis[i][j] = true;
    					if (dfs(i, j, vis, board, word, 1)) return true;
    				}
    			}
    		}
    		return false;
    	}
    	bool dfs(int x, int y, vector<vector<bool>>& vis, vector<vector<char>>& board, string word, int cur) {
    		if (cur == n) return true;
    		for (int i = 0; i < 4; i++) {
    			int nx = x + dx[i], ny = y + dy[i];
    			if (nx < 0 || nx >= H || ny <0 || ny >= W) continue;
    			if (board[nx][ny] == word[cur] && !vis[nx][ny]) {
    				vis[nx][ny] = true;
    				if (dfs(nx, ny, vis, board, word, cur + 1)) return true;
    				vis[nx][ny] = false;
    			}
    		}
    		return false;
    	}
    };
  • 相关阅读:
    asp之缓存 cachestate
    ASP。net 之view
    ASP.net gridview之性别
    asp的gridview
    yii源码学习心得2
    yii源码学习心得
    什么是伪静态?伪静态有何作用?
    Yii2.0 时间日期插件之yii2-timepicker
    yii中调整ActiveForm表单样式
    8个新鲜的PHP常用代码
  • 原文地址:https://www.cnblogs.com/GadyPu/p/5034149.html
Copyright © 2011-2022 走看看