H: 愛滴魔力轉圈圈~~(dfs)

題目描述

Storm有一個m行n列的整數矩陣。c++

他會從(1,1)開始,順時針螺旋訪問該矩陣,每一個元素剛好被訪問一次。數組

請你按Storm的訪問順序輸出每一個元素。
 spa

輸入

第一行輸入整數t,表示有t組數據,0 < t < 50;
第一行輸入兩個數m和n,其中0<m,n≤500;
以後m行,每行n個數以空格隔開,表示這個矩陣。code

輸出

輸出t行,每行表示每組螺旋輸出的結果orm

樣例輸入

1
3 4
1 2 3 4
5 6 7 8
9 10 11 12

樣例輸出

1 2 3 4 8 12 11 10 9 5 6 7 

題意很簡單就是順時針呈螺旋狀將全部數組元素都訪問一遍。

真沒想到又是一道dfs題,經過這道題我也感覺到dfs的強大。


#include <bits/stdc++.h>
using namespace std;
int a[1000][1000] ;
int dir[4][2] = {{0 , 1},{1 , 0},{0 , -1},{-1 , 0}};
int vis[1000][1000];
int y , x ;
void dfs(int m , int n , int di)
{
    cout << a[m][n] << " " ;
    for(int i = 0 ; i < 4 ; i++)
    {
        int newy = m + dir[(i + di) % 4][0] ;
        int newx = n + dir[(i + di) % 4][1] ;
        if(newy >= 1 && newy <= y && newx >= 1 && newx <= x && !vis[newy][newx])
        {
            vis[newy][newx] = 1 ;
            dfs(newy , newx , di + i); // 同過輸出發現一個有趣的現象 i 始終爲0 或 1 全部我將 i < 4 該爲 i < 2 也AC 。
        }//當遇到須要轉彎時 因if()條件不能過進不去。再次循環 i + 1 . 
    }

}
void init()
{
    memset(vis , 0 , sizeof(vis));
}

int main()
{
    int n ;
    cin >> n ;
    while(n--)
    {
        init();
        cin >> y >> x ;
        for(int i = 1 ; i <= y ; i++)
            for(int j = 1 ; j <= x ; j++)
            cin >> a[i][j];
        vis[1][1] = 1 ;//這個標記容易忘記。
        dfs(1 , 1 , 0);
        cout << endl ;
    }

    return 0;
}

 

並非典型的dfs 。一直在深搜 , 而回溯爲空 。 
相關文章
相關標籤/搜索