zoukankan      html  css  js  c++  java
  • Word Search

    描述

    There is a matrix only contains uppercase letters. Try to find a word in this matrix.

    You can go toward four directions (top, bottom, left, right), each position can only be visited once.

    输入

    There are multiple test cases. The first line is a positive integer T, indicating the number of test cases.

    For each test case, the first line contains three integer n, m, q.

    Then a matrix with size of n*m follows. After the matrix are q lines.

    Each line is a word with uppercase letters only. The length of each word is no more than 50.

    (1<=n, m <= 50,1 <= q <= 50)

     输出

    For each test, output q lines. If the word of ith line exists, print "Yes" in the ith line, else print "No".

    Output a blank line after each test case.

    样例输入

    2
    3 4 3
    ABCE
    SFCS
    ADEE
    ABCCED
    SEE
    ABCB
    5 5 5
    YYBDC
    PMFNJ
    KGJKD
    HUAOP
    JMUSB
    MFMYBDCJN
    BXIPOUCIMFVOHFNWO
    KOAUMUSB
    GJNNOB
    CJC

    样例输出

    Yes
    Yes
    No

    No
    No
    Yes
    No
    No

    题目大意:给出一个字符串在矩阵中是否能找到

    解题思路:爆搜看看能不能从矩阵中找出这个字符串

    #include <bits/stdc++.h>
    #define INF 0x3f3f3f3f
    using namespace std;
    const int N=100005;
    char M[55][55],vis[55][55];
    int dir[4][2]={0,1,0,-1,1,0,-1,0};
    int len,n,m,f;
    string s;
    void dfs(int x,int y,int pos)
    {
        if(pos==len-1) f=1;
        if(f==1||x>n||x<1||y>m||y<1) return;
        
        vis[x][y]=1;
        for(int i=0;i<4;i++){
            int xx=x+dir[i][0];
            int yy=y+dir[i][1];
            if(s[pos+1]==M[xx][yy]&&vis[xx][yy]==0) dfs(xx,yy,pos+1);
        }
        vis[x][y]=0;
    }
    int main()
    {
        int k,T,q;
        cin>>T;
        while(T--){
            cin>>n>>m>>q;
            for(int i=1;i<=n;i++){
                for(int j=1;j<=m;j++) cin>>M[i][j]; 
            } 
            for(int i=1;i<=q;i++){
                cin>>s;
                f=0;
                len=s.size();
                for(int a=1;a<=n;a++){
                    for(int b=1;b<=m;b++){
                        if(M[a][b]==s[0]) dfs(a,b,0);    
                    }
                }
                if(f) cout<<"Yes
    ";
                else cout<<"No
    ";
            }
            cout<<"
    ";
            
        }
    }
  • 相关阅读:
    文本框模糊匹配(纯html+jquery简单实现)
    ajax 基础2
    ajax 基础
    Js 实战3(实现全选)
    JS 实战2(邮箱选人功能)
    JS 实战1(添加、删除)
    Js 图片轮播渐隐效果
    Js 手风琴效果
    树上莫队
    洛谷 3676
  • 原文地址:https://www.cnblogs.com/ww123/p/11644316.html
Copyright © 2011-2022 走看看