3 bbwbwbwbw bwwwbwbwb bbbbwbbbw
2459 267 356789
本题主要考察广度搜索方法的应用。首先,注意到本题是操做次数(即生成图的边)最重要,其次才是顶点顺序,那么就要采用以边为搜索线索的广度搜索,而非深搜,深搜会WA。 node
另外,本题最好采用二进制表示棋盘状态,操做简便并且节省运行时间,代码也更简洁,而9种操做对应的是当前状态数和特定数字的异或。另外,状态矩阵是必需的,否则可能会超时。 ios
PS:此题天雷滚滚的地方是,答案必需是1-9的数字,也就是说输入是wwwwwwwww的时候,输出应该是11,卡了我很长时间才搞对。 spa
// Problem#: 1048 // Submission#: 1853201 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <iostream> #include <string> #include <queue> #include <cstring> using namespace std; #define END 0 struct node{ int v; string f; node( int n ){ v = n; f = ""; } node( int n, string s ){ v = n; f = s; } }; int field[10]={0,432,504,216,438,511,219,54,63,27}; bool visit[1<<9]; inline int toi( string s ){ int re = 0; for( int i=0 ; i<9 ; i++ ){ re <<= 1; re |= s[i]=='b' ? 1 : 0 ; } return re; } void bfs( int a ){ queue<node> buffer; buffer.push(node(a)); visit[a] = true; while( !buffer.empty() ){ node temp = buffer.front(); buffer.pop(); if( temp.v==END ){ cout << temp.f << endl; return ; } for( int i=1 ; i<=9 ; i++ ){ int t = temp.v^field[i]; if( !visit[t] ){ visit[t] = true; string s = temp.f; s += '0'+i; buffer.push(node(t,s)); } } } } int main(){ int n; string str; int start; cin >> n; while( n-- ){ cin >> str; start = toi(str); memset(visit,false,sizeof(visit)); if( start==0 ) cout << 11 << endl; else bfs(start); } return 0; }