笔试算法题(01):字符串倒置 & 八皇后问题

出题:将字符串“ABCD1234efgh”进行前后对调;

分析:

  • 常见的考查指针使用的案例,知道字符串长度之后,依次交换位置i以及位置(length-1-i)上的内容,直到重叠;
  • 注意不能直接修改指针变量索引的常量字符串;

解题:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 void reverse(char* target, int length) {
 4         char temp;
 5         int i;
 6         for(i=0;i<length/2;i++) {
 7                 temp=*(target+i);
 8                 *(target+i)=*(target+(length-i-1));
 9                 *(target+(length-i-1))=temp;
10         }
11 }
12 int main(void) {
13         char target[]="0123456789";
14         reverse(target,10);
15         int i;
16         for(i=0;i<10;i++)
17                 printf("%c",target[i]);
18         return EXIT_SUCCESS;
19 }

出题:八皇后问题(8*8的方格上,八个皇后不能互相攻击,也就是任意两个皇后都不会落在同一行,同一列,以及同一斜线上,要求给出所有的情况);

分析:

  • 典型的考查递归的案例,每一行(或者列)有且只能有一个皇后,因此遍历每一行,并测试这一行上的所有对应列的位置

解题:

 1 #include <stdio.h>
 2 /**
 3  * table[k]=0 means wrong position;
 4  * table[k]=1 means possible position;
 5  * table[k]=2 means queen position;
 6  * in order to put 8 queens in 8*8 table, there must be one queen at each line.
 7  *
 8  * */
 9 void InsertQueen(int *table, int v) {
10         for(int h=0;h<8;h++) {
11                 if(table[h+v*8] == 1) {
12                         table[h+v*8]=2;
13                         if(v == 7) {
14                                 ShowResult(table);
15                                 return;
16                         } else {
17                                 Mark(table,h,v);
18                                 InsertQueen(table,v+1);
19                                 Unmark(table,h,v);
20                         }
21                 }
22         }
23 }
24 int main() {
25         int *table=new int[8*8];
26         //initiate 8*8 table to 1
27         for(int i=0;i<8;i++) {
28                 for(int j=0;j<8;j++) {
29                         table[i+j*8]=1;
30                 }
31         }
32         InsertQueen(table,0);
33         delete [] table;
34         return 1;
35 }
原文地址:https://www.cnblogs.com/leo-chen-2014/p/3730425.html