LeetCode : Word Search
来源:互联网 发布:2017php笔试 编辑:程序博客网 时间:2024/04/27 12:16
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
.要考虑输入是 ["aa"], "aaa"的问题。
class Solution {public: bool exist(vector<vector<char> > &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function int nRow = board.size(); if(nRow == 0) return false; if(word.size() == 0) return true; int nCol = board[0].size(); bool res = false; for(int i = 0; i< nRow; ++i){ for(int j = 0; j< nCol; ++j) { if(board[i][j] == word[0]){ board[i][j] = 0; res = sub(board, word.substr(1), i, j); board[i][j] = word[0]; if(res) return res; } } } return res; } bool sub(vector<vector<char> > &board, string word, int row, int col){ if(word.size() == 0) return true; char c = word[0]; int nRow = board.size(); int nCol = board[0].size(); bool res = false; if(row -1 >= 0 &&board[row-1][col] == c){ board[row-1][col] = 0; res = sub(board, word.substr(1), row - 1, col); board[row-1][col] = c; if(res) return true; } if(row + 1 < nRow && board[row + 1][col] == c){ board[row+1][col] = 0; res = sub(board, word.substr(1), row + 1, col); board[row+1][col] = c; if(res) return true; } if(col - 1 >= 0 && board[row][col - 1] == c){ board[row][col - 1] = 0; res = sub(board, word.substr(1), row, col - 1); board[row][col - 1] = c; if(res) return true; } if(col + 1 < nCol && board[row][col + 1] == c){ board[row][col + 1] = 0; res = sub(board, word.substr(1), row, col + 1); board[row][col + 1] = c; if(res) return true; } return false; }};
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- 基于jquery实现的上传图片及图片大小验证、图片预览效果代码!
- LeetCode : Valid Sudoku
- Mule应用架构:1、关于mule
- LeetCode : Validate Binary Search Tree
- LeetCode : Wildcard Matching
- LeetCode : Word Search
- LeetCode : ZigZag Conversion
- 钩子函数动态汉化外文程序菜单(学习收录)
- [Leetcode] Binary Tree Maximum Path Sum
- Remove Element
- Remove Duplicates from Sorted Array II
- Jquery的LigerUI如何实现文件上传(已解决,有实例)
- 商务智能-系统概述-数据整合
- Js、Jquery获得字符串变量的长度函数实例!