笔试算法题(01):字符串倒置 & 八皇后问题
2024-09-06 05:21:03
出题:将字符串“ABCD1234efgh”进行前后对调;
分析:
- 常见的考查指针使用的案例,知道字符串长度之后,依次交换位置i以及位置(length-1-i)上的内容,直到重叠;
- 注意不能直接修改指针变量索引的常量字符串;
解题:
#include <stdio.h>
#include <stdlib.h>
void reverse(char* target, int length) {
char temp;
int i;
for(i=;i<length/;i++) {
temp=*(target+i);
*(target+i)=*(target+(length-i-));
*(target+(length-i-))=temp;
}
}
int main(void) {
char target[]="";
reverse(target,);
int i;
for(i=;i<;i++)
printf("%c",target[i]);
return EXIT_SUCCESS;
}
出题:八皇后问题(8*8的方格上,八个皇后不能互相攻击,也就是任意两个皇后都不会落在同一行,同一列,以及同一斜线上,要求给出所有的情况);
分析:
- 典型的考查递归的案例,每一行(或者列)有且只能有一个皇后,因此遍历每一行,并测试这一行上的所有对应列的位置
解题:
#include <stdio.h>
/**
* table[k]=0 means wrong position;
* table[k]=1 means possible position;
* table[k]=2 means queen position;
* in order to put 8 queens in 8*8 table, there must be one queen at each line.
*
* */
void InsertQueen(int *table, int v) {
for(int h=;h<;h++) {
if(table[h+v*] == ) {
table[h+v*]=;
if(v == ) {
ShowResult(table);
return;
} else {
Mark(table,h,v);
InsertQueen(table,v+);
Unmark(table,h,v);
}
}
}
}
int main() {
int *table=new int[*];
//initiate 8*8 table to 1
for(int i=;i<;i++) {
for(int j=;j<;j++) {
table[i+j*]=;
}
}
InsertQueen(table,);
delete [] table;
return ;
}
最新文章
- [javaSE] 注解-自定义注解
- Kosaraju算法---强联通分量
- 【转】nginx+tomcat+memcached (msm)实现 session同步复制
- 【转载】uclibc和glibc的差别
- [PHP] url的pathinfo模式加载不同控制器的实现
- 安卓自写Adapter
- Oracle触发器Trigger2行级
- poj1207
- BZOJ 2005: [Noi2010]能量采集( 数论 + 容斥原理 )
- SVN 在 Xcode中的状态说明
- CoreJavaE10V1P3.7 第3章 Java的基本编程结构-3.7 输入输出(Input ,Output)
- Shell脚本常用判断
- (cljs/run-at (JSVM. :browser) ";命名空间就这么简单";)
- linux_group总结
- Spring Boot(二):数据库操作
- TypeError: unsupported operand type(s) for +: &#39;float&#39; and &#39;decimal.Decimal&#39;
- WinFormEx
- BZOJ [FJOI2007]轮状病毒 (找规律)
- 深入HBase架构解析(二)【转】
- myEclipse 下配置多个Tomcat
热门文章
- bzoj 1613: [Usaco2008 Jan]Running贝茜的晨练计划【dp】
- spring boot启动报错Error starting ApplicationContext(未能配置数据源)
- tableView 顶部多出一部分解决方法
- quickpow || 快速幂
- _bzoj1088 [SCOI2005]扫雷Mine【dp】
- BZOJ 3224 SBT 普通平衡树
- github下载下来的C#控制台小游戏[含源码]
- lock to deteck in oracle
- dotnet cors 跨域问题
- Android学习笔记(十二) 线程