【发布时间】:2017-12-09 10:33:11
【问题描述】:
我正在尝试做“boggle”游戏,我有一个带有字母的 2D 矩阵,我必须找到单词。 矩阵:包含以下字母:{ {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S ','M','E'}, {'L', 'L', 'P', 'N'} }; 输入:这个矩阵 输出:在矩阵中找到的所有单词,来自字典“isWord”。
代码应采用矩阵、索引、索引、单词和布尔矩阵。 我继续的每个字母都应该在布尔矩阵中标记为真,然后我继续递归直到它的长度。我每次走4条路。我不能只向前走。 仅在一条路径中运行而不在其余路径中继续运行的代码的主要问题。 [调用“checkword”几次,它似乎是第一个命令]。
任何人的想法?在 C 中相当新。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isWord(char *s);
void check(char mat[4][4]) {
int i,j;
int counter=0;
for(i=0; i<4; i++) {
for(j =0; j<4; j++) {
char str[12] = "";
//append(str, mat[i][j]);
bool checker[4][4]={{false}};
//printf("mat[%d][%d]: %s\n", i, j, str);
checkword(mat,i,j, str, checker);
counter++;
fflush(stdout);
}
}
}
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
void checkword(char mat[4][4], int i, int j, char word[], bool checker[4][4])
{
if(i >= 0 && i<4 && j >= 0 && j < 4)
{
if(!checker[i][j])
{
// Mark current cell as visited and append current character
// to str
checker[i][j] = true;
append(word, mat[i][j]);
printf("%s\n", word);
// If str is present in dictionary, then print it
if (isWord(word))
printf("Found word: %s\n", word);
checkword(mat, i+1, j, word, checker);
checkword(mat, i, j+1, word, checker);
checkword(mat, i, j-1, word, checker);
checkword(mat, i-1, j, word, checker);
}
}
}
bool isWord(char* s) {
return (!strcmp(s,"CAT") |
!strcmp(s,"CATS") |
!strcmp(s,"TRAM") |
!strcmp(s,"TRAMS") |
!strcmp(s,"TAME") |
!strcmp(s,"CAR") |
!strcmp(s,"CARS") |
!strcmp(s,"RAT") |
!strcmp(s,"RATS") |
!strcmp(s,"RAMP") |
!strcmp(s,"ART") |
!strcmp(s,"CART") |
!strcmp(s,"STAMP") |
!strcmp(s,"TAKEN") |
!strcmp(s,"MEN") |
!strcmp(s,"MAKE") |
!strcmp(s,"TAKE") |
!strcmp(s,"ATE") |
!strcmp(s,"SELL") |
!strcmp(s,"STEEL") |
!strcmp(s,"RAKE") );
}
int main() {
char mat[4][4] = { {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S','M','E'}, {'L', 'L', 'P', 'N'} };
check(mat);
// printf("Numbers of cells : %d", count);
}
【问题讨论】:
-
给出示例输入、输出和预期输出,并对你的代码做一个小解释,比如代码的哪一部分做什么(仅主要部分)
-
矩阵:包含以下字母:{ {'C','A','R','T'}, {'E', 'T', 'A', 'K'} , {'E','S','M','E'}, {'L','L','P','N'} };输入:这个矩阵输出:在矩阵中找到的所有单词,来自字典“isWord”。代码应采用矩阵、索引、索引、单词和布尔矩阵。我继续的每个字母都应该在布尔矩阵中标记为真,然后我继续递归直到它的长度。我每次走 4 条路。
-
你必须在你的校验词 'checker[i][j]=false;' 的末尾重置为 false,否则它只会在单词中走一条路径。
标签: c