LeetCode -- Word Search
来源:互联网 发布:神周瑜皮肤 知乎 编辑:程序博客网 时间:2024/05/16 14:06
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.
就是在一个字母矩阵中搜索一个单词。如果通过对某个字符进行上下左右移动所构成的路径,可以找到指定单词则返回true。
思路:
从矩阵的每个字符分别出发,进行DFS。
实现代码:
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.
就是在一个字母矩阵中搜索一个单词。如果通过对某个字符进行上下左右移动所构成的路径,可以找到指定单词则返回true。
思路:
从矩阵的每个字符分别出发,进行DFS。
实现代码:
public class Solution { public bool Exist(char[,] board, string word) { RowLen = board.GetLength(0); ColLen = board.GetLength(1); for(var i =0 ;i < RowLen; i++){ for(var j = 0;j < ColLen; j++){ if(TryFind(board, word, i, j, 0)){ return true; } } } return false; }private int RowLen;private int ColLen;public bool TryFind(char[,] board, string word, int row, int col, int i){if(row < 0 || col < 0 || row >= RowLen || col >= ColLen || word[i] != board[row,col]){return false;}if(i == word.Length - 1){return true;}var t = board[row,col];board[row,col] = '%'; if(TryFind(board, word, row-1 , col, i+1)||TryFind(board, word, row+1 , col, i+1)||TryFind(board, word, row , col-1, i+1)||TryFind(board, word, row , col+1, i+1)){return true;}board[row,col] = t;return false;}}
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
- 三种web性能压力测试工具
- 【C++】基础知识—内联(置)函数及register关键字
- LeetCode -- Word Pattern
- perror(const char)
- 我的博客开张了!
- LeetCode -- Word Search
- Java - 关键字 final 的用法总结
- 交叉验证之我见
- 在北大校园BBS引起轰动的一篇文章
- Apache Shiro的(what、why、who)保护你的应用程序
- 逻辑回归、决策树和支持向量机(I)
- JNI Local Reference Changes in ICS
- 计算机视觉领域研究资源及期刊、会议介绍
- centos7安装redis