T_T ++运算符和+1不一样。(i+1)%4 忘带小括号了。bfs函数是bool 型,忘记返回false时的情况了。噢。。。。debug快哭了。。。。。。

DESCRIPTION:
求最少的步骤。使得棋盘上的棋子全黑或者全白。奇数次相当于1次。偶数次相当于不翻。

bfs用来求解最优问题。主要用来求距离初始状态路径最短的路径。思想是暴力枚举+位运算。第一次做位运算的题目。。醉醉的啦。。。。。。

附代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#define end1 65535
#define end2 0
using namespace std;

int step[end1];
bool used[end1];
unsigned short q[end1];
int front = 0, rear = 0;

void init()
{
    char str;
    front = 0, rear = 0;
    unsigned short int begin = 0;
    for (int i=0; i<4; ++i)
    {
        for (int j=0; j<4; ++j)
        {
            cin >> str;
            if (str == 'b')
               begin |= (1 << (i*4 + j));
        }
    }
    memset(step, 0, sizeof(step));
    memset(used, 0, sizeof(used));
    q[rear++] = begin;
    used[begin] = 1;
    step[begin] = 0;
}

unsigned short int move(unsigned short int state, int i)
{
    unsigned short int temp = 0;
    temp |= (1 << i);
    if ((i + 1) % 4 != 0)
        temp |= (1 << (i + 1));
    if (i % 4 != 0)
        temp |= (1 << (i - 1));
    if (i + 4 < 16)
        temp |= (1 << (i + 4));
    if (i - 4 >= 0)
        temp |= (1 << (i - 4));
    return (state^temp);
}

bool bfs()
{
     while (front < rear)
     {
         unsigned short state = q[front++];
         for (int i=0; i<16; ++i)
         {
             unsigned short temp;
             temp = move(state, i);
            if(0 == state || 65535 == state)
            {
              cout << step[state];
              return true;
            }
             else if (!used[temp])
             {
                 q[rear++] = temp;
                 used[temp] = true;
                 step[temp] = step[state]+1;
             }
         }
     }
     return false;
}

int main()
{
    init();
    if (!bfs())
        cout << "Impossible" ;

    char c;
    cin >> c;
    return 0;
}

posted on 2015-06-15 19:44  小小八  阅读(266)  评论(0编辑  收藏  举报