PG-矩陣之對角線

2022.11.10 PM 08:00 by CBJ

來源 : https://drive.google.com/file/d/1CMnis82zw9hGQHW1pRv3LFXACoUGA90Y/view
出題者 : 108資訊學科能力競賽複賽-彰雲嘉
標籤 : 陣列、模擬法
難易度 : 2
解題想法 : 實際對每個對角線做判斷,假如合法則cnt++
//C++ language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/%E8%B3%87%E8%A8%8A%E5%AD%B8%E7%A7%91%E8%83%BD%E5%8A%9B%E7%AB%B6%E8%B3%BD/108%E5%BD%B0%E9%9B%B2%E5%98%89/PG-%E7%9F%A9%E9%99%A3%E4%B9%8B%E5%B0%8D%E8%A7%92%E7%B7%9A.cpp

#include<iostream>
#include<utility>
#define MAXN 10005
using namespace std;
pair<int,int>start;
char square[MAXN][MAXN];
int N;
bool check_right(){
    int x=start.first,y=start.second;
    char pivot=square[x][y];
    while(x<N && x>=0 && y<N && y>=0){
        if(square[x][y]!=pivot){
            return false;
        }
        x++;y++;
    }
    return true;
}
bool check_left(){
    int x=start.first,y=start.second;
    char pivot=square[x][y];
    while(x<N && x>=0 && y<N && y>=0){
        if(square[x][y]!=pivot){
            return false;
        }
        x++;y--;
    }
    return true;
}
int main(){
    int a;cin>>a;
    while(a--){
        cin>>N;
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                cin>>square[i][j];
            }
        }
        int cnt=0;
        for(int i=0;i<N-1;i++){
            start={i,0};
            if(check_right())cnt++;
        }
        for(int j=1;j<N-1;j++){
            start={0,j};
            if(check_right())cnt++;
        }
        for(int j=1;j<N;j++){
            start={0,j};
            if(check_left())cnt++;
        }
        for(int i=1;i<N-1;i++){
            start={i,N-1};
            if(check_left())cnt++;
        }
        cout<<cnt<<"\n";
    }
    return 0;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *