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;
    	}
    };
  • 相关阅读:
    注册表命令大全(二)
    让电脑定时关机
    NSIS nsDialogs 插件
    poj_1562Oil Deposits
    hdoj_1342Lotto
    VS 生成事件文件拷贝
    poj_1111Image Perimeters
    模拟求解迷宫问题(DFS+BFS)
    VS2010如何为所有工程配置环境
    POJ 并查集 题目汇总 ——czyuan原创
  • 原文地址:https://www.cnblogs.com/GadyPu/p/5034149.html
Copyright © 2011-2022 走看看