路徑之謎
題目描述
小明冒充 XX 星球的騎士,進入了一個奇怪的城堡。
城堡里邊什么都沒有,只有方形石頭鋪成的地面。
假設城堡地面是 n×nn×n 個方格。如下圖所示。
按習俗,騎士要從西北角走到東南角。可以橫向或縱向移動,但不能斜著走,也不能跳躍。每走到一個新方格,就要向正北方和正西方各射一箭。(城堡的西墻和北墻內各有 nn 個靶子)同一個方格只允許經過一次。但不必走完所有的方格。如果只給出靶子上箭的數目,你能推斷出騎士的行走路線嗎?有時是可以的,比如上圖中的例子。
本題的要求就是已知箭靶數字,求騎士的行走路徑(測試數據保證路徑唯一)
輸入描述
第一行一個整數 NN (0≤N≤200≤N≤20),表示地面有 N×NN×N 個方格。
第二行 NN 個整數,空格分開,表示北邊的箭靶上的數字(自西向東)
第三行 NN 個整數,空格分開,表示西邊的箭靶上的數字(自北向南)
輸出描述
輸出一行若干個整數,表示騎士路徑。
為了方便表示,我們約定每個小格子用一個數字代表,從西北角開始編號: 0,1,2,3 ??
比如,上圖中的方塊編號為:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
輸入輸出樣例
示例
輸入
4 2 4 3 4 4 3 3 3
輸出
0 4 5 1 2 3 7 11 10 9 13 14 15
好久沒寫都有點生疏,調試了很久。
#include <iostream>
using namespace std;int n, top[25], left1[25], map[25][25];
int res[800][2], idx = 0, flag = 0, started = 0;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};void dfs(int cur_row, int cur_col){//cout<<cur_row<<" "<<cur_col<<endl;if(flag == 1){//cout<< "flag == 1"<<endl;return ;}if(cur_row < 1 || cur_row > n || cur_col < 1 || cur_col > n){//cout<< "out of bound"<<endl;return ; }if(map[cur_row][cur_col] > 1){return ;}int cnt = 0;for(int i=1; i<=n; i++){//cout<<top[i] <<" "<< left1[i]<<endl;if(top[i] < 0 || left1[i] < 0){//cout<< "negative num"<<endl; return ;}cnt += top[i] + left1[i];}if(cur_row == n && cur_col == n && cnt == 0){ //cout<< "yes"<<endl;flag = 1;return ;}for(int i=0; i<4; i++){res[idx][0] = cur_row;res[idx][1] = cur_col;left1[cur_row + dir[i][0]]--;top[cur_col + dir[i][1]]--;map[cur_row + dir[i][0]][cur_col + dir[i][1]] += 1;idx++;dfs(cur_row + dir[i][0], cur_col + dir[i][1]);if(flag == 1){//cout<<"yes--"<<endl;return ;}left1[cur_row + dir[i][0]]++;top[cur_col + dir[i][1]]++;map[cur_row + dir[i][0]][cur_col + dir[i][1]] -= 1;idx--;}
}int main()
{ cin>>n;for(int i=1; i<=n; i++){cin>>top[i];}for(int i=1; i<=n; i++){cin>>left1[i];}map[1][1] = 1;left1[1]--;top[1]--;dfs(1, 1);for(int i=0; i<idx; i++){int num = ( res[i][0] - 1 ) * n + res[i][1] - 1;cout<<num<<" ";}cout<< n * n - 1;return 0;
}