Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
The game of ‘Inverso’ is played on a 3x3 grid of colored fields (each field is either black or white). Each field is numbered as follows:
1 2 3
4 5 6
7 8 9
The player can click on a field, which will result in the inversion of that field and all its direct neighboring fields (i.e. the color changes from black to white or vice-versa). Hence,
Clicking field 1 inverts fields 1, 2, 4, 5
Clicking field 2 inverts fields 1, 2, 3, 4, 5, 6
Clicking field 3 inverts fields 2, 3, 5, 6
Clicking 4 inverts fields 1, 2, 4, 5, 7, 8
Clicking 5 inverts fields all fields
Clicking 6 inverts fields 2, 3, 5, 6, 8, 9
Clicking 7 inverts fields 4, 5, 7, 8
Clicking 8 inverts fields 4, 5, 6, 7, 8, 9
Clicking 9 inverts fields 5, 6, 8, 9
The aim of the game is to find the shortest sequence of clicks to make all fields white from a given start coloring of the grid.
Input
The first line contains a number N (0≤N≤10000) of runs. The following N lines each contain a string of nine letters ‘b’ (black) or ‘w’ (white) for the color of the fields 1 to 9. This is the initial coloring of the grid.
Output
For each input string the shortest word in the letters ‘1’… ‘9’ (for clicking field one, …, nine) which makes all fields white. If there is more than one shortest word then the lexicographically smallest one must be printed (‘1234’ is smaller than ‘1342’).
Sample Input
3bbwbwbwbwbwwwbwbwbbbbbwbbbw
Sample Output
2459 267356789
題目分析:
像圖那樣進行廣度遍曆,但是要設個標記,遍曆過的就不要再遍曆了,還要注意wwwwwwwww輸出11,這個調了半個小時 鬱悶
/**/#include<iostream>#include <iomanip>#include<stdio.h>#include<cmath>#include<iomanip>#include<list>#include <map>#include <vector>#include <string>#include <algorithm>#include <sstream>#include <stack>#include<queue>#include<string.h>using namespace std;int data[9][10]={{1,2,4,5,0},{1,2,3,4,5,6,0},{2,3,5,6,0},{1,2,4,5,7,8,0},{1,2,3,4,5,6,7,8,9,0},{2,3,5,6,8,9,0},{4,5,7,8,0},{4,5,6,7,8,9,0},{5,6,8,9,0}};typedef struct STATUS{unsigned int a;vector<int> record;}status;inline bool judge(int a){if(a==0)return true;return false;}int main(){int n;cin>>n;for(int xx=0;xx<n;xx++){unsigned int gra=0;for(int i=0;i<9;i++)//w是0,b是1{char x;cin>>x;if(x=='b')gra+=pow(2.0,i);}if(gra==0){cout<<11<<endl;continue;}status tmp;tmp.a=gra;bool flag[513];memset(flag,0,sizeof(flag));queue<status> qe;qe.push(tmp);flag[gra]=true;while(1){status wh=qe.front();flag[wh.a]=true;qe.pop();if(judge(wh.a)){for(vector<int>::size_type i=0;i<wh.record.size();i++)cout<<wh.record[i]+1;cout<<endl;break;}for(int i=0;i<9;i++){status tt;tt.a=wh.a;tt.record=wh.record;for(int j=0;j<9&&data[i][j]!=0;j++){unsigned int qw=pow(2.0,data[i][j]-1);tt.a=tt.a^qw;}//end for jif(flag[tt.a]==true)continue;tt.record.push_back(i);qe.push(tt);}//end for i}//end while}}