a107中等二維陣列、座標與鄰居

TOI 2022/05 新手組:單字找找看

將表格與單字統一大小寫,從每格沿八個直線方向比對。

前往題目練習 →回報教學錯誤時間 O(RC×8L) ・ 空間 O(RC+L)

這題在學什麼

將表格與單字統一大小寫,從每格沿八個直線方向比對。

對一個方向先計算終點,終點在圖內才逐字比較。矩形內的直線兩端都在圖內時,中間各格也在圖內。

每次匹配記錄 (起點列,起點行,終點列,終點行),取四元組字典序最小者,不能單憑方向迴圈順序決定答案。單字長一時起終點相同。

Step-by-step animation

八方向搜尋與座標字典序

回報動畫錯誤
步驟 1 / 3

統一大小寫

查詢 bCd 轉成 bcd。

abcd
xbxy
xxcz
xxxd
word
bcd

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <cctype>
using namespace std;
int main(){int r,c; cin>>r>>c; vector<string>a(r); string w;
    for(string &s:a){cin>>s; for(char &ch:s) ch=tolower((unsigned char)ch);}
    cin>>w; for(char &ch:w) ch=tolower((unsigned char)ch);
    array<int,4> best{}; bool found=false; int len=w.size();
    for(int i=0;i<r;++i) for(int j=0;j<c;++j)
      for(int dx=-1;dx<=1;++dx) for(int dy=-1;dy<=1;++dy) if(dx||dy){
        int x=i+dx*(len-1),y=j+dy*(len-1);
        if(x<0||x>=r||y<0||y>=c) continue;
        bool ok=true; for(int k=0;k<len;++k) if(a[i+dx*k][j+dy*k]!=w[k]){ok=false; break;}
        array<int,4> now{i+1,j+1,x+1,y+1};
        if(ok&&(!found||now<best)){found=true; best=now;}
      }
    if(!found) cout<<"NO\n"; else cout<<best[0]<<' '<<best[1]<<'\n'<<best[2]<<' '<<best[3]<<'\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多