LeetCode: Word Search
来源:互联网 发布:c语言less 编辑:程序博客网 时间:2024/06/05 08:20
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
可以通过leetcode平台测试。以下是在visual studio 2015上的测试
思路:
- 遍历整个board
- 搜索到第一个匹配字符
- 搜索当前字符位置的上下左右位置的字符是否匹配并且把上一次搜索到的字符设置为无效字符即’\0’
- 把原位置字符还原
- 注意判断循环的退出条件
// WordSearch.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "iostream"#include "vector"#include "string"using namespace std;class Solution {public: bool exist(vector<vector<char> >&board, string word) { int row = board.size(); int col = board[0].size(); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { if (findCurrAndNext(board, word, i, j, row, col)) { return true; } } return false; } bool findCurrAndNext(vector<vector<char> >& board, string word, int i, int j,int row,int col);};//i j: the location of current search bool Solution::findCurrAndNext(vector<vector<char> >& board, string word, int i, int j,int row, int col){ const char* str=word.c_str();//type is const //the current search location whether Yes if (i < 0 || j < 0 || i >= row || j >= col || board[i][j] == '\0' || *str != board[i][j]) { return false; } //end of word search if (*(str + 1) == '\0') { return true; } //The location of the last search was set to an invalid location char c = board[i][j]; board[i][j] = '\0'; //search up,down,left,right of the current location if (findCurrAndNext(board, str + 1, i - 1, j, row, col) || findCurrAndNext(board, str + 1, i + 1, j, row, col)\ || findCurrAndNext(board, str + 1, i, j - 1, row, col) || findCurrAndNext(board, str + 1, i, j + 1, row, col)) { return true; } //change the last character to the original character board[i][j] = c; return false;}int main(){ string str = "nihao"; const char* c = str.c_str(); cout << *c << endl; system("pause"); return 0;}
阅读全文
0 0
- 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
- c++第六次实验-两点距离
- 简明C语言教程(十七)函数
- Centos7安装Jenkins
- 三个数组随机合并
- [leetcode]: 70. Climbing Stairs
- LeetCode: Word Search
- 简明C语言教程(十九)变量的作用域和存储方式
- Linux安装后要做的事
- 思维的局限
- POJ 3259 Wormholes [图论.判断负环] 《挑战程序设计竞赛》 2.5
- 二分图的概念汇总
- 【数据结构】中的基数排序(BucketSort)
- Python中的列表(上)
- JavaScript中如何实现面向对象编程