簡體   English   中英

在字符矩陣中搜索特定單詞

[英]Searching a particular word in a matrix of characters

我試圖通過C在字符矩陣中搜索特定單詞,但無法找到固定的解決方案。

例如:假設我必須在字符矩陣(3 * 9)中搜索單詞INTELLIGENT (一旦您從矩陣中選擇了一個字符以構成一個句子,就無法再次選擇它來形成相同的句子。從任何一個單元到其所有相鄰單元的路徑。一個鄰居可以共享一條邊或一個角。

IIIINN.LI  
....TTEGL  
.....NELI

輸出:是(可以找到單詞INTELLIGENT)任何人都可以解決上述問題!

使用深度優先搜索。

您可以使用遞歸算法來做到這一點。 找到所有包含第一個字母的(未使用的)位置,然后查看是否可以通過從相鄰的正方形中的一個開始在其余板上找到單詞的其余部分。

#include <stdio.h>

char Matrix[3][9] = {
    { 'I','I','I','I','N','N','.','L','I'},
    { '.','.','.','.','T','T','E','G','L'},
    { '.','.','.','.',',','N','E','L','I'}
};
char Choice[3][9] = { { 0 }, { 0 }, { 0 } };
const char WORD[] = "INTELLIGENT";
const int  Len = sizeof(WORD)-1;
int Path[sizeof(WORD)-1] = { 0 };

char get(int row, int col){
    if(1 > col || col > 9) return '\0';
    if(1 > row || row > 3) return '\0';
    if(Choice[row-1][col-1] || Matrix[row-1][col-1] == '.')
        return '\0';
    else
        return Matrix[row-1][col-1];
}

#define toLoc(r, c) (r)*10+(c)
#define getRow(L) L/10
#define getCol(L) L%10

int search(int loc, int level){
    int r,c,x,y;
    char ch;
    if(level == Len) return 1;//find it
    r = getRow(loc);
    c = getCol(loc);
    ch = get(r,c);
    if(ch == 0 || ch != WORD[level]) return 0;
    Path[level]=toLoc(r,c);
    Choice[r-1][c-1] = 'v';//marking
    for(x=-1;x<=1;++x){
        for(y=-1;y<=1;++y){
            if(search(toLoc(r+y,c+x), level + 1)) return 1;
        }
    }
    Choice[r-1][c-1] = '\0';//reset
    return 0;
}

int main(void){
    int r,c,i;
    for(r=1;r<=3;++r){
        for(c=1;c<=9;++c){
            if(search(toLoc(r,c), 0)){
                printf("YES\nPath:");
                for(i=0;i<Len;++i){
                    printf("(%d,%d)", getRow(Path[i]), getCol(Path[i]));
                }
                printf("\n");
                return 0;
            }
        }
    }
    printf("NO\n");
    return 0;
}

我認為這就是您的意思.....雖然它似乎比您當前提供的要簡單,但是我可能會誤解了這個問題。

我使用Numpy將任意數組重塑為單個字母列表,然后創建搜索項的掩碼和輸入列表的副本。 我在更新遮罩時勾選了每個字母以進行搜索。

import numpy as np
import copy

def findInArray(I,Word):
    M=[list(x) for x in I]

    M=list(np.ravel(M))

    print "Letters to start: %s"%"".join(M)

    Mask=[False]*len(Word)

    T = copy.copy(M)

    for n,v in enumerate(Word):
        try:
            p=T.index(v)
        except ValueError:
            pass
        else:
            T[p]=''
            Mask[n]=True

    print "Letters left over: %s"%"".join(T)            
    if all(Mask):print "Found %s"%Word
    else:print "%s not Found"%Word

    print "\n"

    return all(Mask)


I=["IIIINN.LI","....TTEGL",".....NELI"]

findInArray(I,"INTEL")
findInArray(I,"INTELLIGENT")
findInArray(I,"INTELLIGENCE")

輸出示例

#include <stdio.h>

#define ROW 1
#define COL 11

char Matrix[ROW][COL] = { { 'I','N','T','E','L','L','I','G','E', 'N', 'T'} };
char Choice[ROW][COL] = { { 0 } };
const char WORD[] = "INTELLIGENT";
const int  Len = sizeof(WORD)-1;
int Path[sizeof(WORD)-1] = { 0 };

char get(int row, int col){
    if(1 > col || col > COL) return '\0';
    if(1 > row || row > ROW) return '\0';
    if(Choice[row-1][col-1] || Matrix[row-1][col-1] == '.')
        return '\0';
    else
        return Matrix[row-1][col-1];
}

#define toLoc(r, c) (r)*16+(c)
#define getRow(L) L/16
#define getCol(L) L%16

int search(int loc, int level){
    int r,c,x,y;
    char ch;
    if(level == Len) return 1;//find it
    r = getRow(loc);
    c = getCol(loc);
    ch = get(r,c);
    if(ch == 0 || ch != WORD[level]) return 0;
    Path[level]=toLoc(r,c);
    Choice[r-1][c-1] = 'v';//marking
    for(x=-1;x<=1;++x){
        for(y=-1;y<=1;++y){
            if(search(toLoc(r+y,c+x), level + 1)) return 1;
        }
    }
    Choice[r-1][c-1] = '\0';//reset
    return 0;
}

int main(void){
    int r,c,i;
    for(r=1;r<=ROW;++r){
        for(c=1;c<=COL;++c){
            if(search(toLoc(r,c), 0)){
                printf("YES\nPath:");
                for(i=0;i<Len;++i){
                    printf("(%d,%d)", getRow(Path[i]), getCol(Path[i]));
                }
                printf("\n");
                return 0;
            }
        }
    }
    printf("NO\n");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM